|
1 | 1 | # Collectors |
| 2 | + |
| 3 | +The most common kind of terminal operation you will perform on a stream |
| 4 | +is "collecting" elements into a new collection. |
| 5 | + |
| 6 | +For this you use the `.collect` method along with an implemention of the |
| 7 | +`Collector` interface. |
| 8 | + |
| 9 | +```java |
| 10 | +~void main() { |
| 11 | +List<String> roles = List.of("seer", "clown", "nightmare"); |
| 12 | + |
| 13 | +Function<String, Integer> countVowels = s -> { |
| 14 | + int vowels = 0; |
| 15 | + for (int i = 0; i < s.length(); i++) { |
| 16 | + char c = s.charAt(i); |
| 17 | + if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { |
| 18 | + vowels++; |
| 19 | + } |
| 20 | + } |
| 21 | + return vowels; |
| 22 | +}; |
| 23 | + |
| 24 | +List<Integer> vowelCounts = roles.stream() |
| 25 | + .map(countVowels) |
| 26 | + .collect(Collectors.toList()); |
| 27 | + |
| 28 | +IO.println(vowelCounts); |
| 29 | +~} |
| 30 | +``` |
| 31 | + |
| 32 | +There are implementations available as static methods on the `Collectors` class for |
| 33 | +collecting into `List`s, `Set`s, and even `Map`s. |
| 34 | + |
| 35 | +Because collecting into specifically a `List` is so common, there is |
| 36 | +also a `.toList()` method directly on `Stream` that serves as a shortcut |
| 37 | +for `.collect(Collectors.toUnmodifiableList())`. |
| 38 | + |
| 39 | +```java |
| 40 | +~void main() { |
| 41 | +List<String> roles = List.of("seer", "clown", "nightmare"); |
| 42 | + |
| 43 | +Function<String, Integer> countVowels = s -> { |
| 44 | + int vowels = 0; |
| 45 | + for (int i = 0; i < s.length(); i++) { |
| 46 | + char c = s.charAt(i); |
| 47 | + if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { |
| 48 | + vowels++; |
| 49 | + } |
| 50 | + } |
| 51 | + return vowels; |
| 52 | +}; |
| 53 | + |
| 54 | +// There is also Collectors.toUnmodifiableList |
| 55 | +List<Integer> vowelCountsList = roles.stream() |
| 56 | + .map(countVowels) |
| 57 | + .collect(Collectors.toList()); |
| 58 | + |
| 59 | +IO.println(vowelCountsList); |
| 60 | + |
| 61 | +vowelCountsList = roles.stream() |
| 62 | + .map(countVowels) |
| 63 | + .toList(); |
| 64 | +IO.println(vowelCountsList); |
| 65 | + |
| 66 | +// ...and Collectors.toUnmodifiableSet() |
| 67 | +Set<Integer> vowelCountsSet = roles.stream() |
| 68 | + .map(countVowels) |
| 69 | + .collect(Collectors.toSet()); |
| 70 | +IO.println(vowelCountsSet); |
| 71 | + |
| 72 | +// ...and Collectors.toUnmodifiableMap |
| 73 | +Map<String, Integer> vowelCountsMap = roles.stream() |
| 74 | + .collect(Collectors.toMap( |
| 75 | + s -> s, |
| 76 | + s -> countVowels.apply(s) |
| 77 | + )); |
| 78 | +IO.println(vowelCountsMap); |
| 79 | +~} |
| 80 | +``` |
0 commit comments