Java8 comparator sorting method example explanation
This article mainly introduces the detailed examples of Java 8 comparator sorting method. The example code is introduced in great detail, which has a certain reference value for everyone's study or work. Friends in need can refer to it
The comparator interface in Java 8 provides some static methods that are convenient for us to sort. Let's explain how to use them through examples
Sort integer list (ascending)
List<Integer> list = Arrays.asList(1,4,2,6,8); list.sort(Comparator.naturalOrder()); System.out.println(list);
Sort integer list (descending)
List<Integer> list = Arrays.asList(1,8); list.sort(Comparator.reverSEOrder()); System.out.println(list);
Sort by object attribute (age)
public class Test { public static void main(String[] args) { List<Person> personList = new ArrayList<>(); personList.add(new Person("a",2)); personList.add(new Person("b",4)); personList.add(new Person("c",7)); // 升序 personList.sort(Comparator.comparingInt(Person::getAge)); // 降序 personList.sort(Comparator.comparingInt(Person::getAge).reversed()); System.out.println(personList); } public static class Person { private String name; private Integer age; public Person(String name,Integer age) { this.name = name; this.age = age; } public Integer getAge() { return age; } // ... toString 方法 } }
Sorting is performed according to object attributes (price and speed). It should be noted that sorting can be done in order, and different orders will lead to different results
public class Test { public static void main(String[] args) { List<Computer> list = new ArrayList<>(); list.add(new Computer("xiaomi",4000,6)); list.add(new Computer("sony",5000,4)); list.add(new Computer("dell",5)); list.add(new Computer("mac",6000,8)); list.add(new Computer("micro",6)); // 先以价格(升序)、后再速度(升序) list.sort(Comparator.comparingInt(Computer::getPrice).thenComparingInt(Computer::getSpeed)); // 先以速度(降序)、后再价格(升序) list.sort(Comparator.comparingInt(Computer::getSpeed).reversed().thenComparingInt(Computer::getPrice)); // 先以价格(降序)、后再速度(降序) list.sort(Comparator.comparingInt(Computer::getPrice).thenComparingInt(Computer::getSpeed).reversed()); System.out.println(list); } public static class Computer { private String name; private Integer price; private Integer speed; public Computer(String name,Integer price,Integer speed) { this.name = name; this.price = price; this.speed = speed; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } public Integer getSpeed() { return speed; } public void setSpeed(Integer speed) { this.speed = speed; } // ... toString 方法 } }
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.