Use streams to filter and sum numbers
Description: From the numbers 1 to 10: keep the even ones, square them and print the list and the sum. Then group the words "kiwi", "fig", "apple", "pear", "plum" by their length.
Hint:
IntStream.rangeClosed,filter,map,sumandCollectors.groupingBy.
Solution
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
List<Integer> squares = IntStream.rangeClosed(1, 10)
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.boxed()
.toList();
System.out.println(squares);
System.out.println(squares.stream().mapToInt(Integer::intValue).sum());
Map<Integer, List<String>> byLength = List.of("kiwi", "fig", "apple", "pear", "plum").stream()
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
System.out.println(byLength);
}
}
Output
[4, 16, 36, 64, 100]
220
{3=[fig], 4=[kiwi, pear, plum], 5=[apple]}
How it works
- Each step takes the result of the one before it: filter, then map, then sum.
groupingBymakes a map from the length to the list of words.
Read Java Streams.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |