有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

通过强制转换将java流groupBy转换为嵌套映射

需要从嵌套地图的结构下方按性别计算总数。但是作为Object存储的数据需要在每次迭代中强制转换它。分组后,无法强制转换最后一个叶映射以计算和筛选日期对象

Map<String, Object> total = new HashMap<>();
Map<String, Object> mass = new HashMap<>();
Map<String, Object> ny = new HashMap<>();
Map<String, Object> male = new HashMap<>();
male.put("2021", 17);
male.put("2020", 98);
male.put("lastdate", new Date());
Map<String, Object> female = new HashMap<>();
female.put("2021", 12);
female.put("2020", 87);
female.put("lastdate", new Date());
mass.put("male", male);
mass.put("female", female);
ny.put("male", male);
ny.put("female", female);
total.put("MA", mass);
total.put("NY", ny);

应用于水下

Object mm = total.values().stream().map(x -> (Map<String, Object>) x)
            .map(Map::entrySet).flatMap(Collection::stream)
            .collect(
                    Collectors.groupingBy(Map.Entry::getKey),
                    Collectors.toMap(x -> (Map<String, Object>) x) // Not Working both toMapping() too
            );

/*
Final required output as Map
male=115
female=99
 */

共 (1) 个答案

  1. # 1 楼答案

    这是一种非常不寻常的数据存储方式。我建议你们实施适当的课程,比如性别、年龄、体重等相关领域的人

    但是,如果您想坚持使用数据结构,下面的方法应该可以:

    Map<String,Integer> result =
    total.values()
            .stream()
            .map(e -> (Map<String,Object>) e)
            .findAny()
            .get()
            .entrySet()
            .stream()
            .collect(
                    Collectors.toMap(Map.Entry::getKey,
                            m -> ((Map<String,Object>) m.getValue()).values()
                                    .stream()
                                    .filter(Integer.class::isInstance)
                                    .mapToInt(Integer.class::cast)
                                    .sum()));