Reputation:
I have two collections of different types. The collection are returned by two servicices, that return two findAll() in two repositories.
I want to combine the two collection in a DTO. My DTO is just a combination of all the collections models variables.
This is my code. I tryed a lot of technique, this is one of them. I want to return a CombinationModel collection
List<OneModel> listOne = oneService.oneEndPoint(); // findAll()
List<TwoModel> listTwo = twoService.twoEndPoint(); // findAll()
List<ConbinationModel> list = new ArrayList<>();
list.addAll(listOne);
list.addAll(listTwo);
Upvotes: 0
Views: 1060
Reputation: 848
You have many options here. One could be creating two static constructors in your ConbinationModel
class like:
public static ConbinationModel fromOneModel(OneModel model) {
final ConbinationModel conbinationModel = new ConbinationModel();
conbinationModel.setField(model.getField());
// set other fields
return conbinationModel;
}
public static ConbinationModel fromTwoModel(TwoModel model) {
final ConbinationModel conbinationModel = new ConbinationModel();
conbinationModel.setField(model.getField());
// set other fields
return conbinationModel;
}
And then you could stream over your lists:
List<ConbinationModel> fromListOne = listOne.stream()
.map(ConbinationModel::fromOneModel)
.collect(Collectors.toList());
List<ConbinationModel> fromListTwo = listTwo.stream()
.map(ConbinationModel::fromTwoModel)
.collect(Collectors.toList());
Upvotes: 1