private Integer area;
private String name;
public static List<City> getInstance(Integer number) {
List<City> cityList = new ArrayList<>();
for (int i = 0; i < number; i++) {
City city = new City((int) (Math.random() * 1000), getCitys()[i]);
cityList.add(city);
}
return cityList;
}
private static String[] getCitys() {
String[] citys = {"南京", "上海", "北京", "重庆", "杭州","长沙",null,"","马鞍山","广东"};
return citys;
}
private static String[] getCitys() {
String[] citys = {"南京", "上海", "北京", "重庆", "杭州","长沙",null,"","马鞍山","广东"};
return citys;
}
public static void main(String[] args) {
String[] citys = getCitys();
Arrays.sort(citys, Comparator.comparing((s -> s),Comparator.nullsLast(String::compareTo)));
for (String city : citys) {
System.out.println(city);
}
}
List<City> cityList = City.getInstance(9);
cityList.forEach(System.out::println);
System.out.println("===============");
// Collections.sort(cityList,(City c1,City c2) -> {
// return c1.getArea().compareTo(c2.getArea());
// });
Collections.sort(cityList, Comparator.comparing(City::getArea));
cityList.forEach(System.out::println);
通过传入函数式接口返回比较器
public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
Function<? super T, ? extends U> keyExtractor)
{
Objects.requireNonNull(keyExtractor);
return (Comparator<T> & Serializable)
(c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}
List<City> cityList = City.getInstance(9);
cityList.forEach(System.out::println);
System.out.println("===============");
List<City> collect = cityList.stream().sorted(Comparator.comparing(City::getName,Comparator.nullsLast(String::compareTo))).collect(Collectors.toList());
collect.forEach(System.out::println);
List<City> cityList = City.getInstance(9);
cityList.forEach(System.out::println);
System.out.println("===============");
List<City> collect = cityList.stream().sorted(Comparator.comparing(City::getName,Comparator.nullsFirst(String::compareTo))).collect(Collectors.toList());
collect.forEach(System.out::println);
List<City> cityList = City.getInstance(9);
cityList.forEach(System.out::println);
System.out.println("===============");
List<City> collect = cityList.stream().sorted(Comparator.comparing(City::getName,Comparator.nullsFirst(String::compareTo)).thenComparing(City::getArea)).collect(Collectors.toList());
collect.forEach(System.out::println);