Java8 對集合進行排序

0.根據集合的對象或屬性 正序排序

    0.1根據屬性

List<Goods> collect = goodsList.stream().sorted(Comparator.comparing(Goods::getAmunt)).collect(Collectors.toList());

    0.2根據對象本身,適應於(List<Integer> 或 List<String>)

List<String> collect = list.stream().sorted(Comparator.comparing(Function.identity())).collect(Collectors.toList());

1.根據集合的對象的屬性(Integer)進行排序

    1.1正序

List<Goods> collect = goodsList.stream()
                      .sorted((x,y) -> Integer.compare(x.getAmunt(),y.getAmunt()))
                      .collect(Collectors.toList());

    1.2逆序

List<Goods> collect = goodsList.stream()
                      .sorted((x,y) -> Integer.compare(y.getAmunt(),x.getAmunt()))
                      .collect(Collectors.toList());

2.根據集合的對象的屬性(String)進行排序

    2.1正序


List<Goods> collect = goodsList.stream()
                      .sorted((x,y) -> x.getName().compareTo(y.getName()))
                      .collect(Collectors.toList());

    2.2 逆序

List<Goods> collect = goodsList.stream()
                      .sorted((x,y) -> y.getName().compareto(x.getName()))
                      .collect(Collectors.toList());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章