|
1 | 1 | package com.baeldung.java8; |
2 | 2 |
|
3 | | -import com.baeldung.java8.entity.Human; |
4 | | -import com.google.common.collect.Lists; |
5 | | -import com.google.common.primitives.Ints; |
6 | | -import org.junit.Assert; |
7 | | -import org.junit.Test; |
| 3 | +import static org.hamcrest.Matchers.equalTo; |
8 | 4 |
|
9 | 5 | import java.util.Collections; |
10 | 6 | import java.util.Comparator; |
11 | 7 | import java.util.List; |
| 8 | +import java.util.stream.Collectors; |
12 | 9 |
|
13 | | -import static org.hamcrest.Matchers.equalTo; |
| 10 | +import org.junit.Assert; |
| 11 | +import org.junit.Test; |
| 12 | + |
| 13 | +import com.baeldung.java8.entity.Human; |
| 14 | +import com.google.common.collect.Lists; |
| 15 | +import com.google.common.primitives.Ints; |
14 | 16 |
|
15 | 17 | public class Java8SortUnitTest { |
16 | 18 |
|
@@ -111,5 +113,22 @@ public final void givenInstanceMethod_whenSortingEntitiesByName_thenCorrectlySor |
111 | 113 | humans.sort(Comparator.comparing(Human::getName)); |
112 | 114 | Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12))); |
113 | 115 | } |
| 116 | + |
| 117 | + @Test |
| 118 | + public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { |
| 119 | + final List<String> letters = Lists.newArrayList("B", "A", "C"); |
| 120 | + |
| 121 | + final List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList()); |
| 122 | + Assert.assertThat(sortedLetters.get(0), equalTo("A")); |
| 123 | + } |
114 | 124 |
|
| 125 | + @Test |
| 126 | + public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { |
| 127 | + |
| 128 | + final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); |
| 129 | + final Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName()); |
| 130 | + |
| 131 | + final List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList()); |
| 132 | + Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12))); |
| 133 | + } |
115 | 134 | } |
0 commit comments