stream流排序的各种类型方法

int类型

  List<Integer> list= new ArrayList<>();
        list.add(3);
        list.add(5);
        list.add(1);
        List<Integer> collect = list.stream()
        		.sorted(Comparator.comparingInt(Integer::intValue))
        		.collect(Collectors.toList());
        System.out.println(collect);
        //[1, 3, 5]
        
        //要是相反的话则加上reversed()
        List<Integer> collect = list.stream()
                .sorted(Comparator.comparingInt(Integer::intValue).reversed())
                .collect(Collectors.toList());

String类型

//按照ascii码排序
 List<String> list= new ArrayList<>();
        list.add("a");
        list.add("c");
        list.add("b");
        List<String> collect = list.stream()
                .sorted(Comparator.comparing(String::toString))
                .collect(Collectors.toList());
        System.out.println(collect);
        //[a, b, c]
        
       //按照长度排序
        List<String> list= new ArrayList<>();
        list.add("a1");
        list.add("c11");
        list.add("b111");
        List<String> collect = list.stream()
                .sorted(Comparator.comparing(String::length))
                .collect(Collectors.toList());
        System.out.println(collect);
        //[a1, c11, b111]

Long类型

 List<Long> list= new ArrayList<>();
        list.add(3L);
        list.add(5L);
        list.add(1L);
        List<Long> collect = list.stream()
                .sorted(Comparator.comparingLong(Long::longValue))
                .collect(Collectors.toList());
        System.out.println(collect);
        //[1, 3, 5]

对象类型

List<OutStoreDetail> sortDetailList = outStoreDetails.stream()
                .sorted(Comparator.comparing(OutStoreDetail::getProductType))
                .collect(Collectors.toList());

Map类型

//map类型要注意value中是否存在空值,如果是ConcurrentHashMap则不会出现这个问题
List<Map<String,Object>> list= new ArrayList<>();
        Map<String, Object> m1 = new HashMap<>();
        m1.put("id", 1);
        m1.put("name", "刘一");
        m1.put("age", 28);
        m1.put("height", new BigDecimal("1.92"));
        Map<String, Object> m2 = new HashMap<>();
        m2.put("id", 2);
        m2.put("name", "陈二");
        m2.put("age", 18);
        m2.put("height", new BigDecimal("1.90"));
        list.add(m1);
        list.add(m2);

        List<Map<String, Object>> collect = list.stream()
                .sorted(Comparator.comparing(item -> Integer.parseInt(item.get("age").toString())))
                .collect(Collectors.toList());
        System.out.println(collect);
        //[{name=陈二, id=2, age=18, height=1.90}, {name=刘一, id=1, age=28, height=1.92}]
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值