flatMap and the rest
map turns one element into one element, and flatMap turns one element into any number of them: it takes a function that answers a stream and joins the streams into one. The rest of the step has thin names that do exactly what they say, and one of them, sorted, needs the elements to be comparable.
flatMap
A list of pages, each page a list of words, flattened into one stream of words. List::stream is the function that answers a stream for one page:
import java.util.List;
import java.util.stream.Collectors;
public class Flat {
public static void main(String[] args) {
List<List<String>> pages = List.of(
List.of("a", "b"),
List.of("b", "c"),
List.of("c", "d"));
System.out.println(pages.stream()
.flatMap(List::stream)
.collect(Collectors.toList()));
System.out.println(pages.stream()
.flatMap(List::stream)
.distinct()
.sorted()
.collect(Collectors.toList()));
System.out.println(pages.stream()
.flatMap(List::stream)
.distinct()
.skip(1)
.limit(2)
.collect(Collectors.toList()));
}
}
javac -Xlint:all Flat.java
java Flat
[a, b, b, c, c, d]
[a, b, c, d]
[b, c]
The first line keeps both copies of b and c, because flattening does not remove anything. The second adds distinct and sorted, and the third drops the first element and keeps two, which is skip and limit on the already distinct stream.
A pipeline that needs a list of lists usually needs one of two things: the flattened elements, which is flatMap, or a count per group, which is groupingBy of lesson 087. The wrong answer is a map that leaves the lists in place and a second loop to flatten them.
distinct, sorted, skip and limit
distinct keeps the first occurrence of every element and uses equals to decide, so it works on records and on any class with a correct pair of overrides. sorted with no argument uses the natural order, and sorted(comparator) uses the order it is given. skip(n) drops the first n elements and limit(n) keeps at most n of the rest.
skip past the end answers an empty stream instead of throwing, and that is what the third line of the next program shows: skipping five of three elements leaves nothing to count, which is zero.
takeWhile and dropWhile
The two are ordered filters. takeWhile keeps the elements from the start while the predicate holds and stops at the first failure; dropWhile does the opposite and keeps the rest from that point:
import java.util.List;
import java.util.stream.Collectors;
public class While {
public static void main(String[] args) {
List<Integer> numbers = List.of(2, 4, 6, 7, 8, 10);
System.out.println(numbers.stream().takeWhile(n -> n % 2 == 0).collect(Collectors.toList()));
System.out.println(numbers.stream().dropWhile(n -> n % 2 == 0).collect(Collectors.toList()));
System.out.println(List.of(1, 2, 3).stream().skip(5).count());
}
}
javac -Xlint:all While.java
java While
[2, 4, 6]
[7, 8, 10]
0
The even numbers stop at 7, so takeWhile keeps the three before it and dropWhile keeps the three after it. A filter with the same predicate would keep 2, 4, 6, 8 and 10 and lose the order information that the 7 carries; takeWhile is the step for a prefix, and it is how a stream reads a run of values from a sorted source.
A stream of characters
String.chars() answers an IntStream of the characters, and mapToObj turns it back into a stream of characters or strings. Counting the distinct letters of a text and joining its characters with a dash:
import java.util.stream.Collectors;
public class Chars {
public static void main(String[] args) {
String text = "hello world";
System.out.println(text.chars().mapToObj(c -> (char) c).filter(c -> c != ' ').distinct().count());
System.out.println(text.chars().filter(c -> c == 'l').count());
System.out.println(text.chars()
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining("-")));
}
}
javac -Xlint:all Chars.java
java Chars
7
3
h-e-l-l-o- -w-o-r-l-d
Seven distinct characters without the space: h, e, l, o, w, r and d. The second line counts the three l letters, and the third joins every character including the space, which is why a dash stands on both sides of it. The cast to char is needed because chars() gives ints, and it is the one place in this lesson where a cast is part of the answer.
Exercises
- Flatten a list of sentences into their words and count the distinct ones.
- Sort the flattened words of Flat by length and then alphabetically.
- Use takeWhile on a list of numbers to keep the values below 10 and print them.
- Count the vowels of a sentence with a stream of characters.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
flatMaptake?Answer
A function that answers a stream for each element, and it joins the streams
The function produces a stream per element, and the step concatenates them.
-
What does
distinctuse to decide that two elements are the same?Answer
equals and hashCode
The step keeps the first of each set of equal elements, so the pair of overrides decides.
-
What does
takeWhiledo after the predicate fails?Answer
It stops, and the rest of the stream is not read
It is an ordered filter for a prefix, so the first failure ends the step.
-
What does this program print?
import java.util.List; import java.util.stream.Collectors; public class Q1 { public static void main(String[] args) { List<List<Integer>> groups = List.of(List.of(1, 2), List.of(2, 3)); System.out.println(groups.stream().flatMap(List::stream).collect(Collectors.toList())); } }Answer
[1, 2, 2, 3]
The two inner lists are joined into one stream, keeping both copies of 2.
-
What does this program print?
import java.util.List; import java.util.stream.Collectors; public class Q2 { public static void main(String[] args) { List<Integer> numbers = List.of(5, 3, 5, 1); System.out.println(numbers.stream().distinct().sorted().collect(Collectors.toList())); } }Answer
[1, 3, 5]
The duplicate 5 is removed and the three values are sorted.
-
What does this program print?
import java.util.List; import java.util.stream.Collectors; public class Q3 { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3, 4, 5); System.out.println(numbers.stream().skip(2).limit(2).collect(Collectors.toList())); } }Answer
[3, 4]
Skipping two leaves 3, 4 and 5, and limit keeps two of them.
-
What does this program print?
import java.util.List; import java.util.stream.Collectors; public class Q4 { public static void main(String[] args) { List<Integer> numbers = List.of(2, 4, 5, 6); System.out.println(numbers.stream().takeWhile(n -> n % 2 == 0).collect(Collectors.toList())); System.out.println(numbers.stream().dropWhile(n -> n % 2 == 0).collect(Collectors.toList())); } }Answer
[2, 4] / [5, 6]
The prefix of even numbers ends at 5, and the rest starts with it.
-
What does this program print?
import java.util.List; public class Q5 { public static void main(String[] args) { System.out.println(List.of(1, 2, 3).stream().skip(10).count()); System.out.println(List.of(1, 2, 3).stream().limit(0).count()); } }Answer
0 / 0
Skipping past the end leaves nothing, and a limit of zero keeps nothing.
-
Why does
String.chars()needmapToObjto collect characters?Answer
It answers an IntStream, and the collectors work on objects
The stream holds ints, so each has to be turned into an object before a collector.
-
What does
sorted()without an argument require?Answer
That the elements are Comparable
The natural order comes from compareTo, so a type without it needs a comparator.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev