Collect a stream into a map of groups, count each group, or join strings with separators.
Java · intermediate · 8 min · 29 steps · free
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class CollectorsDemo {
public static void main(String[] args) {
List<String> words = List.of("apple", "avocado", "banana", "blueberry", "cherry");
Map<Character, List<String>> byLetter = words.stream()
.collect(Collectors.groupingBy(w -> w.charAt(0), TreeMap::new, Collectors.toList()));
Map<Character, Long> counts = words.stream()
.collect(Collectors.groupingBy(w -> w.charAt(0), TreeMap::new, Collectors.counting()));
String joined = words.stream()
.filter(w -> w.length() <= 6)
.collect(Collectors.joining(", ", "[", "]"));
System.out.println(byLetter);
System.out.println(counts + " " + joined);
}
}lambda$main$0(), with w = "apple". It gets its own variables on the stack.w changes from "avocado" to "banana".w changes from "banana" to "blueberry".w changes from "blueberry" to "cherry".lambda$main$0() has finished, so its variables are gone.byLetter.lambda$main$1(), with w = "apple". It gets its own variables on the stack.w changes from "apple" to "avocado".w changes from "avocado" to "banana".w changes from "banana" to "blueberry".w changes from "blueberry" to "cherry".lambda$main$1() has finished, so its variables are gone.counts..filter(w -> w.length() <= 6).lambda$main$2(), with w = "apple". It gets its own variables on the stack.w changes from "apple" to "avocado".w changes from "avocado" to "banana".w changes from "banana" to "blueberry".w changes from "blueberry" to "cherry".lambda$main$2() has finished, so its variables are gone.joined.{a=[apple, avocado], b=[banana, blueberry], c=[cherry]}.{a=2, b=2, c=1} [apple, banana, cherry].Answer: A Long count. It counts.
Answer: "a-b". The separator goes between items.
← Streams: reduce, count, max, average · New Collection Methods: removeIf, replaceAll, merge, forEach →