在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()));