Skip to content

Commit d7dac62

Browse files
authored
Merge pull request eugenp#5360 from amit2103/BAEL-9460
[BAEL-9460] - Added code examples of Add section in 'Comparison with …
2 parents bfe0ded + 91efa72 commit d7dac62

1 file changed

Lines changed: 25 additions & 6 deletions

File tree

core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
package com.baeldung.java8;
22

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;
84

95
import java.util.Collections;
106
import java.util.Comparator;
117
import java.util.List;
8+
import java.util.stream.Collectors;
129

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;
1416

1517
public class Java8SortUnitTest {
1618

@@ -111,5 +113,22 @@ public final void givenInstanceMethod_whenSortingEntitiesByName_thenCorrectlySor
111113
humans.sort(Comparator.comparing(Human::getName));
112114
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
113115
}
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+
}
114124

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+
}
115134
}

0 commit comments

Comments
 (0)