1. 程式人生 > >stream sorted進行降序排序

stream sorted進行降序排序

根據value值的大小進行降序排序,並進行擷取。
    public static void main(String[] args) {
        List<Map<String, Object>> list = Lists.newArrayList();
        Map<String, Object> map = Maps.newHashMap();
        map.put("id", 1);
        map.put("value", 20);
        list.add(map);
        map = Maps.newHashMap();
        map.put("id", 2);
        map.put("value", 80);
        list.add(map);
        map = Maps.newHashMap();
        map.put("id", 3);
        map.put("value", 21);
        list.add(map);
        map = Maps.newHashMap();
        map.put("id", 4);
        map.put("value", 28);
        list.add(map);
        System.out.println("原始資料:"+list);
        //根據value進行排序 得到升序排列
        list.sort(Comparator.comparing(h -> ConvertUtil.obj2Integer(h.get("value"))));
        //顛倒排序,變為降序排列
        Collections.reverse(list);
        //擷取前3個
        System.out.println("結果"+list.subList(0, 3));
    }

使用1.8 stream處理

List<Map<String, Object>>result = list.stream().sorted((h1, h2) -> 
//降序
ConvertUtil.obj2Integer(h2.get("value")).compareTo(ConvertUtil .obj2Integer(h1.get("value"))))
				//前3個
                .limit(3)
                //終止流
                .collect(Collectors.toList());
  System.out.println("流結果"+result );
執行結果:
原始資料:[{id=1, value=20}, {id=2, value=80}, {id=3, value=21}, {id=4, value=28}]
結果[{id=2, value=80}, {id=4, value=28}, {id=3, value=21}]