Home > database >  Convert List to Set to group by a an attribute using Java Stream
Convert List to Set to group by a an attribute using Java Stream

Time:08-13

I have a list of object Car which has two attributes int carId, long carSN

1, 123
2, 456
3, 123
1, 789

And I have another set of object CarCombined which has two attributes int carId, Set<Long> carSNs

Is there a way in Java Language using Java Stream (preferably) I can convert that List<Car> to Set<CarCombined> such that it groups by the carId? the new Set<CarCombined> I am looking for should have these values:

1, [123, 789]
2, [456]
3, [123]

CodePudding user response:

Try this

list.stream().collect(groupingBy(Car::getCarId,  mapping(Car::getCarSn, toSet())))
        .entrySet().stream().map(e-> new CarCombined(e.getKey(), e.getValue())).collect(toSet());

First you transform your list into Map<carId, Set<carSn>> and then transform map into CarCombined objects and collect them as Set

  • Related