题解 | #集合排序#
集合排序
https://www.nowcoder.com/practice/4d12899bb255459bbf2b3635b3d32817
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; import java.util.Comparator; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Customer customer1 = new Customer("小明",scanner.nextInt()); Customer customer2 = new Customer("小军",scanner.nextInt()); Customer customer3 = new Customer("小红",scanner.nextInt()); List<Customer> customers = new ArrayList<>(); customers.add(customer1); customers.add(customer2); customers.add(customer3); //write your code here...... // Collections.sort(customers,new Comparator<Customer>(){ // @Override // public int compare(Customer o1,Customer o2){ // return o2.getConsumption() - o1.getConsumption(); // } // }); //lambda简化 Collections.sort(customers,(Customer o1,Customer o2) -> o2.getConsumption() - o1.getConsumption()); System.out.println(customers); } } class Customer{ private String name; private int consumption; public Customer(String name, int consumption) { this.name = name; this.consumption = consumption; } public int getConsumption(){ return consumption; } @Override public String toString() { return "Customer{" + "name='" + name + '\'' + ", consumption=" + consumption + '}'; } //write your code here...... }