java list集合按名稱排序,再按年齡排序,最後按工資排序。
阿新 • • 發佈:2018-12-25
public static void main(String[] args) { List<User> list=new ArrayList<User>(); User user=new User(); user.setAge(31); user.setName("d"); user.setSal(8000.35); User user2=new User(); user2.setAge(25); user2.setName("a"); user2.setSal(6500.35); User user3=new User(); user3.setAge(20); user3.setName("c"); user3.setSal(7000.35); User user4=new User(); user4.setAge(18); user4.setName("c"); user4.setSal(3500.35); User user5=new User(); user5.setAge(20); user5.setName("a"); user5.setSal(3500.35); User user6=new User(); user6.setAge(18); user6.setName("c"); user6.setSal(1200.35); list.add(user); list.add(user2); list.add(user3); list.add(user4); list.add(user5); list.add(user6); System.out.println("----------------------------排序前-----------------------------------------"); for(int i=0;i<list.size();i++) { System.out.println(list.get(i).getName()+" | "+list.get(i).getAge()+" | "+list.get(i).getSal()); } System.out.println("----------------------------排序後-----------------------------------------"); // 排序 Collections.sort(list, new Comparator<User>() { @Override public int compare(User o1, User o2) { //按名稱排序 int flag=o1.getName().compareTo(o2.getName()); //這是升降, o2.getName().compareTo(o1.getName()) ---》這是降序 (下面同理) //按年齡排序 if(flag==0) { flag=o1.getAge()-o2.getAge(); } //按工資排序 if(flag==0) { flag=(int)(o1.getSal()-o2.getSal()); } return flag; } }); for(int i=0;i<list.size();i++) { System.out.println(list.get(i).getName()+" | "+list.get(i).getAge()+" | "+list.get(i).getSal()); } }
實體類
public class User { private int age; //用年齡 private String name; //使用者名稱 private double sal; //工資 public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSal() { return sal; } public void setSal(double sal) { this.sal = sal; } }