Skip to content

Commit eb1afcb

Browse files
Merge branch 'pr/496-gregorz-collectors'
2 parents 7fcdee3 + ea9cb32 commit eb1afcb

4 files changed

Lines changed: 272 additions & 20 deletions

File tree

‎core-java-8/.project‎

Lines changed: 0 additions & 17 deletions
This file was deleted.

‎core-java-8/README.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,12 @@
33
## Core Java 8 Cookbooks and Examples
44

55
### Relevant Articles:
6-
// - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
6+
- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
77
- [Java – Directory Size](http://www.baeldung.com/java-folder-size)
88
- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
9+
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
10+
- [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
911
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
1012
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
11-
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
13+
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
14+
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)

‎core-java-8/pom.xml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,8 @@
6666
<dependency>
6767
<groupId>org.assertj</groupId>
6868
<artifactId>assertj-core</artifactId>
69-
<version>3.4.1</version>
69+
<version>3.5.1</version>
70+
<scope>test</scope>
7071
</dependency>
7172

7273
<dependency>
Lines changed: 265 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,265 @@
1+
package com.baeldung.collectors;
2+
3+
import com.google.common.collect.ImmutableList;
4+
import com.google.common.collect.ImmutableSet;
5+
import com.google.common.collect.Sets;
6+
import org.junit.Test;
7+
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+
39+
public class Java8CollectorsTest {
40+
41+
private final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
42+
43+
@Test
44+
public void whenCollectingToList_shouldCollectToList() throws Exception {
45+
final List<String> result = givenList.stream()
46+
.collect(toList());
47+
48+
assertThat(result)
49+
.containsAll(givenList);
50+
}
51+
52+
@Test
53+
public void whenCollectingToList_shouldCollectToSet() throws Exception {
54+
final Set<String> result = givenList.stream()
55+
.collect(toSet());
56+
57+
assertThat(result)
58+
.containsAll(givenList);
59+
}
60+
61+
@Test
62+
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
63+
final List<String> result = givenList.stream()
64+
.collect(toCollection(LinkedList::new));
65+
66+
assertThat(result)
67+
.containsAll(givenList)
68+
.isInstanceOf(LinkedList.class);
69+
}
70+
71+
@Test
72+
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
73+
assertThatThrownBy(() -> {
74+
givenList.stream()
75+
.collect(toCollection(ImmutableList::of));
76+
}).isInstanceOf(UnsupportedOperationException.class);
77+
78+
}
79+
80+
@Test
81+
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
82+
final Map<String, Integer> result = givenList.stream()
83+
.collect(toMap(Function.identity(), String::length));
84+
85+
assertThat(result)
86+
.containsEntry("a", 1)
87+
.containsEntry("bb", 2)
88+
.containsEntry("ccc", 3)
89+
.containsEntry("dd", 2);
90+
}
91+
92+
@Test
93+
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
94+
final Map<String, Integer> result = givenList.stream()
95+
.collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
96+
97+
assertThat(result)
98+
.containsEntry("a", 1)
99+
.containsEntry("bb", 2)
100+
.containsEntry("ccc", 3)
101+
.containsEntry("dd", 2);
102+
}
103+
104+
@Test
105+
public void whenCollectingAndThen_shouldCollect() throws Exception {
106+
final List<String> result = givenList.stream()
107+
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
108+
109+
assertThat(result)
110+
.containsAll(givenList)
111+
.isInstanceOf(ImmutableList.class);
112+
}
113+
114+
@Test
115+
public void whenJoining_shouldJoin() throws Exception {
116+
final String result = givenList.stream()
117+
.collect(joining());
118+
119+
assertThat(result)
120+
.isEqualTo("abbcccdd");
121+
}
122+
123+
@Test
124+
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
125+
final String result = givenList.stream()
126+
.collect(joining(" "));
127+
128+
assertThat(result)
129+
.isEqualTo("a bb ccc dd");
130+
}
131+
132+
@Test
133+
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
134+
final String result = givenList.stream()
135+
.collect(joining(" ", "PRE-", "-POST"));
136+
137+
assertThat(result)
138+
.isEqualTo("PRE-a bb ccc dd-POST");
139+
}
140+
141+
@Test
142+
public void whenPartitioningBy_shouldPartition() throws Exception {
143+
final Map<Boolean, List<String>> result = givenList.stream()
144+
.collect(partitioningBy(s -> s.length() > 2));
145+
146+
assertThat(result)
147+
.containsKeys(true, false)
148+
.satisfies(booleanListMap -> {
149+
assertThat(booleanListMap.get(true))
150+
.contains("ccc");
151+
152+
assertThat(booleanListMap.get(false))
153+
.contains("a", "bb", "dd");
154+
});
155+
}
156+
157+
@Test
158+
public void whenCounting_shouldCount() throws Exception {
159+
final Long result = givenList.stream()
160+
.collect(counting());
161+
162+
assertThat(result)
163+
.isEqualTo(4);
164+
}
165+
166+
@Test
167+
public void whenSummarizing_shouldSummarize() throws Exception {
168+
final DoubleSummaryStatistics result = givenList.stream()
169+
.collect(summarizingDouble(String::length));
170+
171+
assertThat(result.getAverage())
172+
.isEqualTo(2);
173+
assertThat(result.getCount())
174+
.isEqualTo(4);
175+
assertThat(result.getMax())
176+
.isEqualTo(3);
177+
assertThat(result.getMin())
178+
.isEqualTo(1);
179+
assertThat(result.getSum())
180+
.isEqualTo(8);
181+
}
182+
183+
@Test
184+
public void whenAveraging_shouldAverage() throws Exception {
185+
final Double result = givenList.stream()
186+
.collect(averagingDouble(String::length));
187+
188+
assertThat(result)
189+
.isEqualTo(2);
190+
}
191+
192+
@Test
193+
public void whenSumming_shouldSum() throws Exception {
194+
final Double result = givenList.stream()
195+
.collect(summingDouble(String::length));
196+
197+
assertThat(result)
198+
.isEqualTo(8);
199+
}
200+
201+
@Test
202+
public void whenMaxingBy_shouldMaxBy() throws Exception {
203+
final Optional<String> result = givenList.stream()
204+
.collect(maxBy(Comparator.naturalOrder()));
205+
206+
assertThat(result)
207+
.isPresent()
208+
.hasValue("dd");
209+
}
210+
211+
@Test
212+
public void whenGroupingBy_shouldGroupBy() throws Exception {
213+
final Map<Integer, Set<String>> result = givenList.stream()
214+
.collect(groupingBy(String::length, toSet()));
215+
216+
assertThat(result)
217+
.containsEntry(1, newHashSet("a"))
218+
.containsEntry(2, newHashSet("bb", "dd"))
219+
.containsEntry(3, newHashSet("ccc"));
220+
}
221+
222+
223+
@Test
224+
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
225+
final ImmutableSet<String> result = givenList.stream()
226+
.collect(toImmutableSet());
227+
228+
assertThat(result)
229+
.isInstanceOf(ImmutableSet.class)
230+
.contains("a", "bb", "ccc", "dd");
231+
232+
}
233+
234+
private static <T> ImmutableSetCollector<T> toImmutableSet() {
235+
return new ImmutableSetCollector<>();
236+
}
237+
238+
private static class ImmutableSetCollector<T> implements Collector<T, ImmutableSet.Builder<T>, ImmutableSet<T>> {
239+
240+
@Override
241+
public Supplier<ImmutableSet.Builder<T>> supplier() {
242+
return ImmutableSet::builder;
243+
}
244+
245+
@Override
246+
public BiConsumer<ImmutableSet.Builder<T>, T> accumulator() {
247+
return ImmutableSet.Builder::add;
248+
}
249+
250+
@Override
251+
public BinaryOperator<ImmutableSet.Builder<T>> combiner() {
252+
return (left, right) -> left.addAll(right.build());
253+
}
254+
255+
@Override
256+
public Function<ImmutableSet.Builder<T>, ImmutableSet<T>> finisher() {
257+
return ImmutableSet.Builder::build;
258+
}
259+
260+
@Override
261+
public Set<Characteristics> characteristics() {
262+
return Sets.immutableEnumSet(Characteristics.UNORDERED);
263+
}
264+
}
265+
}

0 commit comments

Comments
 (0)