且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按对象属性将地图分组到新地图

更新时间:2022-12-30 18:10:54

使用现有模型以及嵌套分组的初始方法,您正在朝正确的方向思考.可以考虑在迭代条目时变平Map的值部分.

With the use of existing models, and the initial approach of nested grouping you were thinking in the right direction. The improvement could be made in thinking about flattening the value part of the Map while iterating over the entries.

allCarsAndBrands.entrySet().stream()
        .flatMap(e -> e.getValue().stream()
                .map(car -> new AbstractMap.SimpleEntry<>(e.getKey(), car)))

一旦有了,分组概念的工作原理几乎相同,但是现在默认的返回分组值将是条目类型.因此,进一步需要mapping.这使整体解决方案类似于:

Once you have that, the grouping concept works pretty much the same, but now the default returned grouped values would instead be of the entry type. Hence a mapping is further required. This leaves the overall solution to be something like :

Map<CarType, Map<CarBrand, List<Car>>> mappedCars =
        allCarsAndBrands.entrySet().stream()
                .flatMap(e -> e.getValue().stream()
                        .map(car -> new AbstractMap.SimpleEntry<>(e.getKey(), car)))
                .collect(Collectors.groupingBy(e -> e.getValue().getType(),
                        Collectors.groupingBy(Map.Entry::getKey,
                                Collectors.mapping(Map.Entry::getValue,
                                        Collectors.toList()))));