Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate objects into collections in Java using streams

I have a list of objects of structure

public class SimpleObject {
    private TypeEnum type;
    private String propA;
    private Integer propB;
    private String propC;
}

which I would like to "pack" into the following objects

public class ComplexObject {
    private TypeEnum type;
    private List<SimpleObject> simpleObjects;
}

based on TypeEnum.
In other words I'd like to create a sort of aggregations which will hold every SimpleObject that contains a certain type. I thought of doing it with Java 8 streams but I don't know how.

So let's say I'm getting the list of SimpleObjects like

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DataService {
    private final DataRepository dataRepo;

    public void getPackedData() {
        dataRepo.getSimpleObjects().stream()...
    }

}

How the next steps should look like? Thank you in advance for any help

I'm using Java 14 with Spring Boot

like image 412
big_OS Avatar asked Apr 13 '26 21:04

big_OS


1 Answers

You can use Collectors.groupingBy to group by type which return Map<TypeEnum, List<SimpleObject>>. Then again stream over map's entryset to convert into List<ComplexObject>

List<ComplexObject> res = 
     dataRepo.getSimpleObjects()
        .stream()
        .collect(Collectors.groupingBy(SimpleObject::getType)) //Map<TypeEnum, List<SimpleObject>>
        .entrySet()
        .stream()
        .map(e -> new ComplexObject(e.getKey(), e.getValue()))  // ...Stream<ComplexObject>
        .collect(Collectors.toList());
like image 163
Eklavya Avatar answered Apr 15 '26 11:04

Eklavya