Added code examples of Add section in 'Comparison with Lambdas' article
package com.baeldung.java8;
-import com.baeldung.java8.entity.Human;
-import com.google.common.collect.Lists;
-import com.google.common.primitives.Ints;
-import org.junit.Assert;
-import org.junit.Test;
+import static org.hamcrest.Matchers.equalTo;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
+import java.util.stream.Collectors;
-import static org.hamcrest.Matchers.equalTo;
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.baeldung.java8.entity.Human;
+import com.google.common.collect.Lists;
+import com.google.common.primitives.Ints;
public class Java8SortUnitTest {
@@ -112,4 +114,21 @@ public class Java8SortUnitTest {
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
+ @Test
+ public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
+ final List<String> letters = Lists.newArrayList("B", "A", "C");
+
+ final List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList());
+ Assert.assertThat(sortedLetters.get(0), equalTo("A"));
+ }
+
+ @Test
+ public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
+
+ final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
+ final Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
+
+ final List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
+ Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
+ }
}
