Skip to content

Commit 2d0f3b2

Browse files
author
Grzegorz Piwowarek
committed
Add Java8 Collectors examples
1 parent e93772a commit 2d0f3b2

1 file changed

Lines changed: 224 additions & 0 deletions

File tree

Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,76 +1,300 @@
11
package com.baeldung.collectors;
22

3+
import com.google.common.collect.ImmutableList;
4+
import com.google.common.collect.ImmutableSet;
5+
import com.google.common.collect.Sets;
36
import org.junit.Test;
47

8+
import java.util.Arrays;
9+
import java.util.Comparator;
10+
import java.util.DoubleSummaryStatistics;
11+
import java.util.LinkedList;
12+
import java.util.List;
13+
import java.util.Map;
14+
import java.util.Optional;
15+
import java.util.Set;
16+
import java.util.function.BiConsumer;
17+
import java.util.function.BinaryOperator;
18+
import java.util.function.Function;
19+
import java.util.function.Supplier;
20+
import java.util.stream.Collector;
21+
22+
import static com.google.common.collect.Sets.newHashSet;
23+
import static java.util.stream.Collectors.averagingDouble;
24+
import static java.util.stream.Collectors.collectingAndThen;
25+
import static java.util.stream.Collectors.counting;
26+
import static java.util.stream.Collectors.groupingBy;
27+
import static java.util.stream.Collectors.joining;
28+
import static java.util.stream.Collectors.maxBy;
29+
import static java.util.stream.Collectors.partitioningBy;
30+
import static java.util.stream.Collectors.summarizingDouble;
31+
import static java.util.stream.Collectors.summingDouble;
32+
import static java.util.stream.Collectors.toCollection;
33+
import static java.util.stream.Collectors.toList;
34+
import static java.util.stream.Collectors.toMap;
35+
import static java.util.stream.Collectors.toSet;
36+
import static org.assertj.core.api.Assertions.assertThat;
37+
import static org.assertj.core.api.Assertions.assertThatThrownBy;
38+
539
public class Java8CollectorsTest {
640

741
@Test
842
public void whenCollectingToList_shouldCollectToList() throws Exception {
43+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
44+
45+
final List<String> result = givenList.stream()
46+
.collect(toList());
947

48+
assertThat(result)
49+
.containsAll(givenList);
1050
}
1151

1252
@Test
1353
public void whenCollectingToList_shouldCollectToSet() throws Exception {
54+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
1455

56+
final Set<String> result = givenList.stream()
57+
.collect(toSet());
58+
59+
assertThat(result)
60+
.containsAll(givenList);
1561
}
1662

1763
@Test
1864
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
65+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
66+
67+
final List<String> result = givenList.stream()
68+
.collect(toCollection(LinkedList::new));
1969

70+
assertThat(result)
71+
.containsAll(givenList)
72+
.isInstanceOf(LinkedList.class);
2073
}
2174

2275
@Test
2376
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
77+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
78+
79+
assertThatThrownBy(() -> {
80+
givenList.stream()
81+
.collect(toCollection(ImmutableList::of));
82+
}).isInstanceOf(UnsupportedOperationException.class);
2483

2584
}
2685

2786
@Test
2887
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
88+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
89+
90+
final Map<String, Integer> result = givenList.stream()
91+
.collect(toMap(Function.identity(), String::length));
92+
93+
assertThat(result)
94+
.containsEntry("a", 1)
95+
.containsEntry("bb", 2)
96+
.containsEntry("ccc", 3)
97+
.containsEntry("dddd", 4);
98+
}
99+
100+
@Test
101+
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
102+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
103+
104+
final Map<String, Integer> result = givenList.stream()
105+
.collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
29106

107+
assertThat(result)
108+
.containsEntry("a", 1)
109+
.containsEntry("bb", 2)
110+
.containsEntry("ccc", 3)
111+
.containsEntry("dddd", 4);
30112
}
31113

32114
@Test
33115
public void whenCollectingAndThen_shouldCollect() throws Exception {
116+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
34117

118+
final List<String> result = givenList.stream()
119+
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
120+
121+
assertThat(result)
122+
.containsAll(givenList)
123+
.isInstanceOf(ImmutableList.class);
35124
}
36125

37126
@Test
38127
public void whenJoining_shouldJoin() throws Exception {
128+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
129+
130+
final String result = givenList.stream()
131+
.collect(joining());
132+
133+
assertThat(result)
134+
.isEqualTo("abbcccdddd");
135+
}
136+
137+
@Test
138+
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
139+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
140+
141+
final String result = givenList.stream()
142+
.collect(joining(" "));
143+
144+
assertThat(result)
145+
.isEqualTo("a bb ccc dddd");
146+
}
147+
148+
@Test
149+
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
150+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
151+
152+
final String result = givenList.stream()
153+
.collect(joining(" ", "PRE-", "-POST"));
39154

155+
assertThat(result)
156+
.isEqualTo("PRE-a bb ccc dddd-POST");
40157
}
41158

42159
@Test
43160
public void whenPartitioningBy_shouldPartition() throws Exception {
161+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
44162

163+
final Map<Boolean, List<String>> result = givenList.stream()
164+
.collect(partitioningBy(s -> s.length() > 2));
165+
166+
assertThat(result)
167+
.containsKeys(true, false)
168+
.satisfies(booleanListMap -> {
169+
assertThat(booleanListMap.get(true))
170+
.contains("ccc", "dddd");
171+
172+
assertThat(booleanListMap.get(false))
173+
.contains("a", "bb");
174+
});
45175
}
46176

47177
@Test
48178
public void whenCounting_shouldCount() throws Exception {
179+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
180+
181+
final Long result = givenList.stream()
182+
.collect(counting());
49183

184+
assertThat(result)
185+
.isEqualTo(4);
50186
}
51187

52188
@Test
53189
public void whenSummarizing_shouldSummarize() throws Exception {
190+
final List<Double> givenList = Arrays.asList(1d, 2d, 3d, 2d);
54191

192+
final DoubleSummaryStatistics result = givenList.stream()
193+
.collect(summarizingDouble(d -> d));
194+
195+
assertThat(result.getAverage())
196+
.isEqualTo(2);
197+
assertThat(result.getCount())
198+
.isEqualTo(4);
199+
assertThat(result.getMax())
200+
.isEqualTo(3);
201+
assertThat(result.getMin())
202+
.isEqualTo(1);
203+
assertThat(result.getSum())
204+
.isEqualTo(8);
55205
}
56206

57207
@Test
58208
public void whenAveraging_shouldAverage() throws Exception {
209+
final List<Double> givenList = Arrays.asList(1d, 2d, 3d, 2d);
210+
211+
final Double result = givenList.stream()
212+
.collect(averagingDouble(d -> d));
59213

214+
assertThat(result)
215+
.isEqualTo(2);
60216
}
61217

62218
@Test
63219
public void whenSumming_shouldSum() throws Exception {
220+
final List<Double> givenList = Arrays.asList(1d, 2d, 3d, 2d);
221+
222+
final Double result = givenList.stream()
223+
.collect(summingDouble(d -> d));
64224

225+
assertThat(result)
226+
.isEqualTo(8);
65227
}
66228

67229
@Test
68230
public void whenMaxingBy_shouldMaxBy() throws Exception {
231+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
232+
233+
final Optional<String> result = givenList.stream()
234+
.collect(maxBy(Comparator.naturalOrder()));
235+
236+
assertThat(result)
237+
.isPresent()
238+
.hasValue("dddd");
239+
}
240+
241+
@Test
242+
public void whenGroupingBy_shouldGroupBy() throws Exception {
243+
final List<String> givenList = Arrays.asList("a", "b", "bb", "ccc", "dddd");
244+
245+
final Map<Integer, Set<String>> result = givenList.stream()
246+
.collect(groupingBy(String::length, toSet()));
69247

248+
assertThat(result)
249+
.containsEntry(1, newHashSet("a", "b"))
250+
.containsEntry(2, newHashSet("bb"))
251+
.containsEntry(3, newHashSet("ccc"))
252+
.containsEntry(4, newHashSet("dddd"));
70253
}
71254

255+
72256
@Test
73257
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
258+
final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dddd");
259+
260+
final ImmutableSet<String> result = givenList.stream()
261+
.collect(toImmutableSet());
262+
263+
assertThat(result)
264+
.isInstanceOf(ImmutableSet.class)
265+
.contains("a", "bb", "ccc", "dddd");
266+
267+
}
268+
269+
private static <T> ImmutableSetCollector<T> toImmutableSet() {
270+
return new ImmutableSetCollector<>();
271+
}
272+
273+
private static class ImmutableSetCollector<T> implements Collector<T, ImmutableSet.Builder<T>, ImmutableSet<T>> {
274+
275+
@Override
276+
public Supplier<ImmutableSet.Builder<T>> supplier() {
277+
return ImmutableSet::builder;
278+
}
279+
280+
@Override
281+
public BiConsumer<ImmutableSet.Builder<T>, T> accumulator() {
282+
return ImmutableSet.Builder::add;
283+
}
284+
285+
@Override
286+
public BinaryOperator<ImmutableSet.Builder<T>> combiner() {
287+
return (left, right) -> left.addAll(right.build());
288+
}
289+
290+
@Override
291+
public Function<ImmutableSet.Builder<T>, ImmutableSet<T>> finisher() {
292+
return ImmutableSet.Builder::build;
293+
}
74294

295+
@Override
296+
public Set<Characteristics> characteristics() {
297+
return Sets.immutableEnumSet(Characteristics.UNORDERED);
298+
}
75299
}
76300
}

0 commit comments

Comments
 (0)