3

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

1

2 Answers 2

2

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());
Sign up to request clarification or add additional context in comments.

Comments

2

You can achieve this with Collectors.groupingBy and further conversion of entries to a list of objects using Collectors.collectingAndThen.

List<SimpleObject> list = ...
List<ComplexObject> map = list.stream()
   .collect(Collectors.collectingAndThen(
       Collectors.groupingBy(SimpleObject::getType),                // group by TypeEnum
          map -> map.entrySet()                                     // map entries to ..
             .stream()
             .map(e -> new ComplexObject(e.getKey(), e.getValue())) // .. ComplexObject
             .collect(Collectors.toList())));                       // .. to List

I am not currently aware of another solution as long as Stream API is not friendly in processing dictionary structures.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.