A stream is a pipeline over a collection: words.stream().filter(w -> w.length() > 3).map(String::toUpperCase).collect(Collectors.toList()) keeps the long words, upper-cases them, and gathers the result into a new list. Nothing happens until the terminal operation at the end (collect, count, sum, forEach, anyMatch). mapToInt(...) gives a stream of numbers with sum(), max(), and average().
Collectors has the useful gatherers: toList(), joining(", "), groupingBy(f) (a map from each key to the list of items with it), and groupingBy(f, Collectors.summingLong(x -> 1L)) (a map from key to how many, as Long; full Java also has Collectors.counting() for this, which the browser runtime does not have yet). Streams read well for filter-map-collect chains; a plain loop is still fine when the logic gets tangled.
The library project reports how many books each author has in the catalog; the class Reports in this lesson counts them with groupingBy and summingLong.
List<Integer> squares = List.of(1, 2, 3, 4).stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList()); // [4, 16]
int total = List.of(1, 2, 3).stream().mapToInt(n -> n).sum(); // 6Your task
In Main, write static List<String> longUpper(List<String> words) returning the words longer than 3 characters in upper case, static int sumOfSquares(List<Integer> xs), and static String joined(List<String> words) returning the words joined with ", ".
In the class Reports, write static Map<String, Long> countByAuthor(List<String> authors) returning how many times each author appears, using groupingBy with summingLong.
Part of the final project. Reports counts the books in the catalog per author. It is saved in this browser and loaded into Project: the library when you get there.
Hint 1
words.stream().filter(w -> w.length() > 3).map(String::toUpperCase).collect(Collectors.toList())
Hint 2
sumOfSquares: xs.stream().mapToInt(n -> n * n).sum(). joined: words.stream().collect(Collectors.joining(", ")). countByAuthor: authors.stream().collect(Collectors.groupingBy(a -> a, Collectors.summingLong(a -> 1L)))
Show the solution
import java.util.*;
import java.util.stream.*;
public class Main {
static List<String> longUpper(List<String> words) {
return words.stream().filter(w -> w.length() > 3).map(String::toUpperCase).collect(Collectors.toList());
}
static int sumOfSquares(List<Integer> xs) {
return xs.stream().mapToInt(n -> n * n).sum();
}
static String joined(List<String> words) {
return words.stream().collect(Collectors.joining(", "));
}
public static void main(String[] args) {
System.out.println(longUpper(List.of("tea", "coffee")) + " " + sumOfSquares(List.of(1, 2, 3)));
}
}
class Reports {
static Map<String, Long> countByAuthor(List<String> authors) {
return authors.stream().collect(Collectors.groupingBy(a -> a, Collectors.summingLong(a -> 1L)));
}
}