java list排序

 

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章