Skip to content

Commit 2aa4e80

Browse files
crorKevinGilmore
authored andcommitted
toSet, toMap: adding examples with duplicates (eugenp#6264)
* BAEL-2548 fix typo * BAEL-2548 toSet, toMap: added tests with duplicate elements
1 parent e49d46d commit 2aa4e80

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

‎core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
public class Java8CollectorsUnitTest {
4040

4141
private final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
42+
private final List<String> listWithDuplicates = Arrays.asList("a", "bb", "c", "d", "bb");
4243

4344
@Test
4445
public void whenCollectingToList_shouldCollectToList() throws Exception {
@@ -48,12 +49,19 @@ public void whenCollectingToList_shouldCollectToList() throws Exception {
4849
}
4950

5051
@Test
51-
public void whenCollectingToList_shouldCollectToSet() throws Exception {
52+
public void whenCollectingToSet_shouldCollectToSet() throws Exception {
5253
final Set<String> result = givenList.stream().collect(toSet());
5354

5455
assertThat(result).containsAll(givenList);
5556
}
5657

58+
@Test
59+
public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception {
60+
final Set<String> result = listWithDuplicates.stream().collect(toSet());
61+
62+
assertThat(result).hasSize(4);
63+
}
64+
5765
@Test
5866
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
5967
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
@@ -83,6 +91,13 @@ public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
8391
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
8492
}
8593

94+
@Test
95+
public void givenContainsDuplicateElements_whenCollectingToMap_shouldThrowException() throws Exception {
96+
assertThatThrownBy(() -> {
97+
listWithDuplicates.stream().collect(toMap(Function.identity(), String::length));
98+
}).isInstanceOf(IllegalStateException.class);
99+
}
100+
86101
@Test
87102
public void whenCollectingAndThen_shouldCollect() throws Exception {
88103
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));

0 commit comments

Comments
 (0)