Press "Enter" to skip to content

常用Java Stream用法

本文持续更新,未完待续。。。

List<Map<String, Object>>格式按照某一个属性进行正序排列

public static void main(String[] args) {
        List<Map<String, Object>> bannerList = new ArrayList<>();
        Map<String, Object> banner1 = new HashMap<>();
        banner1.put("weight", 1);
        Map<String, Object> banner2 = new HashMap<>();
        banner2.put("weight", 2);
        Map<String, Object> banner3 = new HashMap<>();
        banner3.put("weight", 0);
        bannerList.add(banner1);
        bannerList.add(banner2);
        bannerList.add(banner3);
        bannerList = bannerList.stream()
                .sorted(Comparator.comparing((o) -> MapUtils.getInteger(o, "weight", 0)))
                .collect(Collectors.toList());
        System.out.println(bannerList);
    }

List<Map<String, Object>>格式按照某一个属性进行倒序排列

public static void main(String[] args) {
        List<Map<String, Object>> bannerList = new ArrayList<>();
        Map<String, Object> banner1 = new HashMap<>();
        banner1.put("weight", 1);
        Map<String, Object> banner2 = new HashMap<>();
        banner2.put("weight", 2);
        Map<String, Object> banner3 = new HashMap<>();
        banner3.put("weight", 0);
        bannerList.add(banner1);
        bannerList.add(banner2);
        bannerList.add(banner3);
        bannerList = bannerList.stream()
                .sorted(Comparator.comparing((o) -> MapUtils.getInteger(o, "weight", 0), Comparator.reverseOrder()))
                .collect(Collectors.toList());
        System.out.println(bannerList);
    }
发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注