首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用groupBy 8流将对象属性映射到另一个对象?

问如何使用groupBy 8流将对象属性映射到另一个对象?
EN

Stack Overflow用户
提问于 2019-01-18 12:29:25
回答 5查看 5.5K关注 0票数 19

假设我有一组保险杠车,它们的两边都有一个大小、颜色和标识符(“汽车代码”)。

代码语言:javascript
复制
class BumperCar {
    int size;
    String color;
    String carCode;
}

现在,我需要将保险杠汽车映射到一个List of DistGroup对象,每个对象都包含属性size、color和汽车代码的List。

代码语言:javascript
复制
class DistGroup {
    int size;
    Color color;
    List<String> carCodes;

    void addCarCodes(List<String> carCodes) {
        this.carCodes.addAll(carCodes);
    }
}

例如,

代码语言:javascript
复制
[
    BumperCar(size=3, color=yellow, carCode=Q4M),
    BumperCar(size=3, color=yellow, carCode=T5A),
    BumperCar(size=3, color=red, carCode=6NR)
]

应导致:

代码语言:javascript
复制
[
    DistGroup(size=3, color=yellow, carCodes=[ Q4M, T5A ]),
    DistGroup(size=3, color=red, carCodes=[ 6NR ])
]

我尝试了以下方法,这实际上是我想要做的事情。但问题是,它将中间结果(转化为Map)具体化,我还认为可以立即完成(可能使用mapping、collectingAndThen或reducing或其他什么),从而产生更优雅的代码。

代码语言:javascript
复制
List<BumperCar> bumperCars = …;
Map<SizeColorCombination, List<BumperCar>> map = bumperCars.stream()
    .collect(groupingBy(t -> new SizeColorCombination(t.getSize(), t.getColor())));

List<DistGroup> distGroups = map.entrySet().stream()
    .map(t -> {
        DistGroup d = new DistGroup(t.getKey().getSize(), t.getKey().getColor());
        d.addCarCodes(t.getValue().stream()
            .map(BumperCar::getCarCode)
            .collect(toList()));
        return d;
    })
    .collect(toList());

在不使用变量作为中间结果的情况下,如何获得所需的结果?

编辑:,如何在不实现中间结果的情况下获得所需的结果?我只是在寻找一种没有实现中间结果的方法,至少在表面上不是这样。这意味着我不想使用这样的东西:

代码语言:javascript
复制
something.stream()
    .collect(…) // Materializing
    .stream()
    .collect(…); // Materializing second time

当然,如果可能的话。

请注意,为了简洁起见,我省略了getter和构造函数。您还可以假设equals和hashCode方法是正确实现的。还请注意,我使用的是SizeColorCombination,我使用它作为组按键。这个类显然包含属性size和color__。还可以使用Tuple__、Pair__、Entry或代表两个任意值组合的任何其他类。

编辑__:当然,也可以使用ol‘skool for循环,但这不在这个问题的范围之内。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2019-01-18 12:56:22

如果我们假设DistGroup具有基于size和color的hashCode/equals,您可以这样做:

代码语言:javascript
复制
bumperCars
    .stream()
    .map(x -> {
        List<String> list = new ArrayList<>();
        list.add(x.getCarCode());
        return new SimpleEntry<>(x, list);
    })
    .map(x -> new DistGroup(x.getKey().getSize(), x.getKey().getColor(), x.getValue()))
    .collect(Collectors.toMap(
        Function.identity(),
        Function.identity(),
        (left, right) -> {
            left.getCarCodes().addAll(right.getCarCodes());
            return left;
        }))
    .values(); // Collection<DistGroup>
票数 8
EN

Stack Overflow用户

发布于 2019-01-18 12:38:55

解决方案-1

只是将这两个步骤合并为一个步骤:

代码语言:javascript
复制
List<DistGroup> distGroups = bumperCars.stream()
        .collect(Collectors.groupingBy(t -> new SizeColorCombination(t.getSize(), t.getColor())))
        .entrySet().stream()
        .map(t -> {
            DistGroup d = new DistGroup(t.getKey().getSize(), t.getKey().getColor());
            d.addCarCodes(t.getValue().stream().map(BumperCar::getCarCode).collect(Collectors.toList()));
            return d;
        })
        .collect(Collectors.toList());

解决方案-2

如果您可以使用groupingBy两次使用属性并将值映射为代码的List,则中间变量会更好,如下所示:

代码语言:javascript
复制
Map<Integer, Map<String, List<String>>> sizeGroupedData = bumperCars.stream()
        .collect(Collectors.groupingBy(BumperCar::getSize,
                Collectors.groupingBy(BumperCar::getColor,
                        Collectors.mapping(BumperCar::getCarCode, Collectors.toList()))));

只需使用forEach将以下内容添加到最终列表中:

代码语言:javascript
复制
List<DistGroup> distGroups = new ArrayList<>();
sizeGroupedData.forEach((size, colorGrouped) ->
        colorGrouped.forEach((color, carCodes) -> distGroups.add(new DistGroup(size, color, carCodes))));

注意:我已经更新了您的构造函数,以便它接受卡片代码列表。

代码语言:javascript
复制
DistGroup(int size, String color, List<String> carCodes) {
    this.size = size;
    this.color = color;
    addCarCodes(carCodes);
}

进一步将第二个解决方案合并成一个完整的声明(尽管我自己也会诚实地支持forEach ):

代码语言:javascript
复制
List<DistGroup> distGroups = bumperCars.stream()
        .collect(Collectors.groupingBy(BumperCar::getSize,
                Collectors.groupingBy(BumperCar::getColor,
                        Collectors.mapping(BumperCar::getCarCode, Collectors.toList()))))
        .entrySet()
        .stream()
        .flatMap(a -> a.getValue().entrySet()
                .stream().map(b -> new DistGroup(a.getKey(), b.getKey(), b.getValue())))
        .collect(Collectors.toList());
票数 2
EN

Stack Overflow用户

发布于 2019-01-18 15:00:28

您可以通过使用以BiConsumer为参数的(HashMap<SizeColorCombination, DistGroup> res, BumperCar bc)进行收集。

代码语言:javascript
复制
Collection<DistGroup> values = bumperCars.stream()
        .collect(HashMap::new, (HashMap<SizeColorCombination, DistGroup> res, BumperCar bc) -> {
                SizeColorCombination dg = new SizeColorCombination(bc.color, bc.size);
                DistGroup distGroup = res.get(dg);
                if(distGroup != null) {
                    distGroup.addCarCode(bc.carCode);
                }else {
                    List<String> codes = new ArrayList();
                    distGroup = new DistGroup(bc.size, bc.color, codes);
                    res.put(dg, distGroup);
                }
                },HashMap::putAll).values();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54254064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档