How to groupBy object properties and map to another object using Java 8 Streams?

后端 未结 4 1468
梦如初夏
梦如初夏 2021-02-19 01:02

Suppose I have a group of bumper cars, which have a size, a color and an identifier (\"car code\") on their sides.

class BumperCar {
    int size;
    String col         


        
4条回答
  •  一向
    一向 (楼主)
    2021-02-19 01:39

    If we assume that DistGroup has hashCode/equals based on size and color, you could do it like this:

    bumperCars
        .stream()
        .map(x -> {
            List 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
    

提交回复
热议问题