I have List<Object[]> inner join MySQL query, I need to create a map key id and value object.
The Code below works, but how to do it best with Streams?
Map<Object, List<Object[]>> convert(List<Object[]> objects) {
Map<Object, List<Object[]>> objectListMap = objects.stream()
.collect(Collectors.toMap(obj -> obj[0], obj -> {
List<Object[]> list = new ArrayList<>();
list.add(obj);
return list;
}, (obj1, obj2) -> {
obj1.addAll(obj2);
return obj1;
}));
return objectListMap;
}
Object[] objects structure:
objects[0] = person id
...
objects[10] = event id
...
objects[15] = event name
This query found all the person with the event visited, but the index in the objects array from 0 to 10 may be the same, 11-15 always change.
And I want to merge all object-lists that have the same id (objects[0]).
next for each value in Map > convert to POJO:
PersonWithEvent converToEntity(List<Object[]> objects) {
Optional< PersonWithEvent > personWithEvent =
objects.stream()
.findFirst().map(obj -> {
PersonWithEvent p = new PersonWithEvent();
p.setId((Integer) obj[0]);
...
return p;
});
personWithEvent.ifPresent(p -> {
List<PersonEvent> personEvents = objects.stream()
.map(obj -> {
PersonEvent pe = new PersonEvent();
pe.setName((String) obj[2]);
...
return pe;
})
.collect(Collectors.toList());
p.setPersonEvents(personEvents);
});
return personWithEvent.get();
And Is it possible to do it for one stream?
List<Object[]>? What are the keys and what the values for the map? What is themergefunction supposed to do?Object[]array has an id at index0and you want to map this id to the rest whole array likeobjects[0] => objects. And additionally you want to merge all object-lists that have the same id (objects[0]).