java8Lombok类库使用List常用提取排序统计

public void test() {
        List zhy = new ArrayList<>();
        zhy.add(new Zhy("two", 2));
        zhy.add(new Zhy("three", 3));
        zhy.add(new Zhy("three2", 3));
        zhy.add(new Zhy("one", 1));

        // 提取code到新list
        List codes = zhy.stream().map(Zhy::getCode).collect(Collectors.toList());
        // 根据code进行排序
        zhy.sort(Comparator.comparingInt(Zhy::getCode));
        // 根据name进行排序
        zhy.sort(Comparator.comparing(Zhy::getName));
        // 统计code重复数量
        Map map = new TreeMap<>();
        for (Object i : zhy) {
            if (map.get(i) == null) {
                map.put(i, 1);
            } else {
                map.put(i, map.get(i) + 1);
            }
        }
        // 简化写法
        for (Object i : zhy) {
            map.merge(i, 1, (a, b) -> a + b);
        }
        /*
        merge 的方法有三个参数 第一个是所选map的key,第二个是需要合并的值,第三个是 如何合并,也就是说合并方法的具体实现
        */
       // map根据value排序
        List> list = new ArrayList<>(map.entrySet());
        list.sort(Comparator.comparingInt(Map.Entry::getValue));
        System.out.println(list);
    }

    @Data
    @AllArgsConstructor
    public class Zhy {
        private String name;
        private int code;
    }

 

你可能感兴趣的:(java后台)