赞
踩
重写compare方法的比较:
升序:
o1>o2,return 1 或 o1<o2,return -1
降序:
o1>o2,return -1 或 o1<o2,return 1
//实体类 static class User{ private Integer age; private Integer score; @Override public String toString() { return "User{" + "age=" + age + ", score=" + score + '}'; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } } //实现Comparator接口 public static class ComparatorSort implements Comparator<User> { @Override public int compare(User o1, User o2) { if (o1.getAge() > o2.getAge()) { return 1; } else if (o1.getAge() < o2.getAge()) { return -1; } else { //当age相等时按照score排序 if (o1.getScore() > o2.getScore()) { return 1; } else { return -1; } } } } //枚举插入数据 public static void main(String[] args) { List<User> list = new ArrayList(); User user1 = new User(); user1.setAge(32); user1.setScore(456); list.add(user1); User user2 = new User(); user2.setAge(15); user2.setScore(532); list.add(user2); User user3 = new User(); user3.setAge(19); user3.setScore(234); list.add(user3); User user4 = new User(); user4.setAge(32); user4.setScore(234); list.add(user4); }
调用重写的compare方法
//调用重写的compare方法排序
Collections.sort(list, new ComparatorSort());
//如果要对最终结果逆序排序,可以使用reverse
Collections.reverse(list);
使用stream排序
多条件使用:thenComparing进行排序
//替换compare方法的排序,只对年龄排序 list = list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList()); //只对年龄排序,使用reversed倒序 list = list.stream(). sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList()); //年龄逆序,成绩顺序排列 list = list.stream() .sorted(Comparator.comparing(User::getAge).reversed().thenComparing(User::getScore)) .collect(Collectors.toList()); //年龄和成绩逆序排列 list = list.stream().sorted(Comparator.comparing(User::getAge) .reversed() .thenComparing(Comparator.comparing(User::getScore).reversed())) .collect(Collectors.toList());
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。