[英]Collect List<Object> to Map<String, List<Object>> in Java 8 using stream
[英]java stream List<Object[]> to Map<Object, List<Object[]>>
我有List<Object[]>
內連接MySQL查詢 ,我需要創建一個map key id和value 對象 。
下面的代碼有效,但如何最好地使用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
此查詢找到所有訪問過該事件的人,但對象數組中從0到10的索引可能相同,11-15總是更改。
我想合並所有具有相同id(對象[0])的對象列表。
Map中的每個值的下一個>轉換為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();
是否有可能為一個流做?
看來你需要在數組Object
索引零處按元素分組
Collectors.groupingBy
按鍵分組
Map<Object, List<Object[]>> map = objects.stream()
.collect(Collectors.groupingBy(o -> o[0]));
使用空和空檢查
Map<Object, List<Object[]>> map = objects.stream()
.filter(o -> o != null && o.length != 0)
.collect(Collectors.groupingBy(o -> o[0]));
例
List<Object[]> objects = new ArrayList<>();
objects.add(new Object[] { 0, 1, 2, 3, 4, 5 });
objects.add(new Object[] { 1, 1, 2, 3, 4, 5 });
objects.add(new Object[] { 2, 1, 2, 3, 4, 5 });
objects.add(new Object[] { 0, 6, 7, 8, 9 });
Map<Object, List<Object[]>> map = objects.stream()
.collect(Collectors.groupingBy(o -> o[0]));
System.out.println(map);
輸出就像
{
0 = [[Ljava.lang.Object;@378bf509,
[Ljava.lang.Object;@5fd0d5ae],
1 = [[Ljava.lang.Object;@2d98a335],
2 = [[Ljava.lang.Object;@16b98e56]
}
你可以看到0
有兩個List<Object[]>
值分組
我會讓整個過程更加明確和清晰。 使用具有大量注釋和良好變量名稱的混合樣式。
在閱讀,理解和維護代碼時,這應該會有很大幫助。
Map<Object, List<Object[]>> convert(List<Object[]> entities) {
Map<Object, List<Object[]>> idToEntitesWithSameId = new HashMap<>();
entities.forEach(entity -> {
// Create an entry for each entity,
// merge with entities of same id
Object id = entity[0];
// Get current value or empty list
List<Object[]> entitiesWithId = idToEntitesWithSameId
.computeIfAbsent(id, ArrayList::new);
// Add own entity, merge with other
// entities of same id
Arrays.stream(entity).forEach(entitiesWithId::add);
});
return idToEntitesWithSameId;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.