Java8中Collectors.groupingBy的坑,分组乱序

先创建个实体

@Data
public class User {
    private String date;
    private String name;
    private String age;

    public User(String date, String name, String age) {
        this.date = date;
        this.name = name;
        this.age = age;
    }
}

按日期分下组

    public static void main(String[] args) {
        List<User> userList = new ArrayList<>();
        for (int x = 1; x < 30; x++) {
            User user = new User("2021-06-" + (x < 10 ? "0" + x : x), "张三", x);
            userList.add(user);
        }

        Map<String, List<User>> userMap = userList.stream().collect(Collectors.groupingBy(User::getDate));
        System.out.println(userMap);
    }

可以看到分完组的Map顺序是乱的
Java8中Collectors.groupingBy的坑,分组乱序_第1张图片
这个方法为什么会乱序,看下源码

    public static <T, K, A, D>
    Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
                                          Collector<? super T, A, D> downstream) {
        return groupingBy(classifier, HashMap::new, downstream);
    }

可以看到,这个方法默认返回的是HashMap,都知道HashMap是无序的,既然找到问题就好解决了,我们手动传个有序的Map进去就可以了

    public static void main(String[] args) {
        List<User> userList = new ArrayList<>();
        for (int x = 1; x < 30; x++) {
            User user = new User("2021-06-" + (x < 10 ? "0" + x : x), "张三", x);
            userList.add(user);
        }

        Map<String, List<User>> userMap = userList.stream().collect(Collectors.groupingBy(User::getDate, LinkedHashMap::new, Collectors.toList()));
        System.out.println(userMap);
    }

可以看到分完组的Map变成有序的了
Java8中Collectors.groupingBy的坑,分组乱序_第2张图片

也可以额外的去除排序

		// 将日期key取出,去重、排序
        List<String> dateList = new ArrayList<>(userMap.keySet());
        dateList = dateList.stream().distinct().collect(Collectors.toList());
        Collections.sort(dateList);
        List<String> dateList= userList.stream().map(User::getDate).collect(Collectors.toList());
        // (日期 + 时点)抽取Map
        Map<String, Double> dataMap = dataList.stream().collect(Collectors.toMap(v -> v.getIssue() + " " + v.getTimeValue(), UserDO::getValue));
		// List属性求和
		Double sumValue = dataList.stream().filter(v -> v.getValue() != null).mapToDouble(v -> v.getValue().doubleValue()).sum();

你可能感兴趣的:(Java,java)