Created
February 6, 2018 18:54
-
-
Save JorgenRingen/0888fc4a10d0dd29035318c3c17c4cae to your computer and use it in GitHub Desktop.
Testing chained comparators from java 8 (about 10% decrease in performance compared to pre-java8 implementation)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Java8ComparatorTest { | |
@Test | |
public void testJava8ChainedComparators() { | |
Comparator<Person> personComparator = Comparator.comparingInt(Person::getAge) | |
.thenComparing(Person::getName) | |
.thenComparing(Person::getOccupation, (o1, o2) -> { | |
return o1.compareTo(o2); | |
}); | |
List<Person> people = Arrays.asList( | |
new Person(11, "b", "c"), | |
new Person(10, "a", "b"), | |
new Person(10, "b", "a")); | |
people.sort(personComparator); | |
Person firstPerson = people.get(0); | |
assertThat(firstPerson.getAge()).isEqualTo(10); | |
assertThat(firstPerson.getName()).isEqualTo("a"); | |
assertThat(firstPerson.getOccupation()).isEqualTo("b"); | |
} | |
class Person { | |
private Integer age; | |
private String name; | |
private String occupation; | |
public Person(Integer age, String name, String occupation) { | |
this.age = age; | |
this.name = name; | |
this.occupation = occupation; | |
} | |
public Integer getAge() { | |
return age; | |
} | |
public String getName() { | |
return name; | |
} | |
public String getOccupation() { | |
return occupation; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment