????1??????
???????????????????????????????????JDK 8???????????JDK 8???????????е?Lambda????——??????????????????дComparator???????Collection??????????
?????????????Baeldung???“Java ——???????”??“Java – Back to Basic”????е???????
????????????????????????????????
public class Human {
private String name;
private int age;
public Human() {
super();
}
public Human(final String name?? final int age) {
super();
this.name = name;
this.age = age;
}
// standard getters and setters
}
????2???????Lambda?????????????
??????Java 8??????????????????Comparator????????????????????????
????new Comparator<Human>() {
????@Override
????public int compare(Human h1?? Human h2) {
????return h1.getName().compareTo(h2.getName());
????}
????}
????????????????Human????б????????
@Test
public void givenPreLambda_whenSortingEntitiesByName_thenCorrectlySorted() {
List<Human> humans = Lists.newArrayList(new Human("Sarah"?? 10)?? new Human("Jack"?? 12));
Collections.sort(humans?? new Comparator<Human>() {
@Override
public int compare(Human h1?? Human h2) {
return h1.getName().compareTo(h2.getName());
}
});
Assert.assertThat(humans.get(0)?? equalTo(new Human("Jack"?? 12)));
}
????3?????Lambda?????????????
????????Lambda?????????????????????????????????????ü???????????????????????
????(final Human h1?? final Human h2) -> h1.getName().compareTo(h2.getName());
????????????????????????????????????????????
????@Test
????public void whenSortingEntitiesByName_thenCorrectlySorted() {
????List<Human> humans = Lists.newArrayList(new Human("Sarah"?? 10)?? new Human("Jack"?? 12));
????humans.sort((Human h1?? Human h2) -> h1.getName().compareTo(h2.getName()));
????Assert.assertThat(humans.get(0)?? equalTo(new Human("Jack"?? 12)));
????}
??????????????????μ?sort API?????API??Java 8??????java.util.List ——????????Collections.sort API??