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
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With