在java8以后使用增强版的Comparator接口:
List<IdNameBean> beans = new ArrayList<>();
beans.add(new IdNameBean(1, "张三"));
beans.add(new IdNameBean(1, "李四"));
方法一:
根据id排序
Collections.sort(beans, Comparator.comparing(IdNameBean::getId));
倒序:
Collections.sort(beans, Comparator.comparing(IdNameBean::getId).reversed());
方法二:
默认升序:
List<IdNameBean> newBeans = beans.stream().sorted(Comparator.comparing(IdNameBean::getId))
.collect(Collectors.toList())
倒序:
List<IdNameBean> newBeans = beans.stream().sorted(Comparator.comparing(IdNameBean::getId).reversed()) .collect(Collectors.toList())
方法三:使用lamda表达式
newBeans.sort((IdNameBean h1, IdNameBean h2) -> h1.getId().compareTo(h2.getId()));
或
newBeans.sort((h1, h2) -> h1.getId().compareTo(h2.getId()));