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

后端 未结 4 1458
梦如初夏
梦如初夏 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 02:03

    You can collect by by using BiConsumer that take (HashMap res, BumperCar bc) as parameters

    Collection values = bumperCars.stream()
            .collect(HashMap::new, (HashMap 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 codes = new ArrayList();
                        distGroup = new DistGroup(bc.size, bc.color, codes);
                        res.put(dg, distGroup);
                    }
                    },HashMap::putAll).values();
    

提交回复
热议问题