Java8??Lambda?????????Comparator??????
???????????? ???????[ 2015/3/9 14:30:02 ] ????????Java ??????? ???
????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??
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11