I have a domain class View
:
public class View {
private String id;
private String docId;
private String name;
// constructor, getters, etc.
}
And there's a list of View
objects.
Elements having the same id
, only differ in one field docId
(the second attribute), example:
List<View> viewList = new ArrayList<>();
viewList.add(new View("1234", "ab123", "john"));
viewList.add(new View("1234", "cd456", "john"));
viewList.add(new View("1234", "ef789", "john"));
viewList.add(new View("5678", "jh987", "jack"));
viewList.add(new View("5678", "ij654", "jack"));
viewList.add(new View("5678", "kl321", "jack"));
viewList.add(new View("9876", "mn123", "ben"));
viewList.add(new View("9876", "op456", "ben"));
}
A and I want to convert them into list of aggregated objects NewView
.
NewView
class look like this:
public static class NewView {
private String id;
private String name;
private List<String> docId = new ArrayList<>();
}
Expected Output for the sample data provided above would be:
{
"id": "1234",
"name": "john",
"docIds": ["ab123", "cd456", "ef789"]
},
{
"id": "5678",
"name": "jack",
"docIds": ["jh987", "ij654", "kl321"]
},
{
"id": "9876",
"name": "ben",
"docIds": ["mn123", "op456"]
}
I've tried something like this:
Map<String, List<String>> docIdsById = viewList.stream()
.collect(groupingBy(
View::getId,
Collectors.mapping(View::getDocId, Collectors.toList())
));
Map<String, List<View>> views = viewList.stream()
.collect(groupingBy(View::getId));
List<NewView> newViewList = new ArrayList<>();
for (Map.Entry<String, List<View>> stringListEntry : views.entrySet()) {
View view = stringListEntry.getValue().get(0);
newViewList.add(new NewView(
view.getId(),
view.getName(),
docIdsById.get(stringListEntry.getKey()))
);
}
Can I create a list of NewView
in only one Stream?