[英]Java 8 extracting/coverting List<Object> into Map<String, List<String>> using stream()
Trying to figure out how can i use the new Java 8 feature .stream() in my code effectively. 试图找出如何有效地在我的代码中使用新的Java 8特性.stream()。
Here is my code in general 这是我的一般代码
List<Item> list = db.query(sqlStatement, (rs, i) -> new Item(rs));
Map<String, List<Item>> itemsByName = new HashMap<>();
for (Item m : list) {
if (!itemsByName.containsKey(m.getName())) {
ArrayList<Item> items = new ArrayList<>();
items.add(m);
itemsByName.put(m.getName(), items);
} else {
itemsByName.get(m.getName()).add(m);
}
}
By this (1) 由此(1)
List<Item> list = db.query(sqlStatement, (rs, i) -> new Item(rs));
I get the List of Items which looks like: 我得到的项目列表看起来像:
list(0): Name1:Value1 list(0):Name1:Value1
list(1): Name1:Value2 list(1):Name1:Value2
list(2): Name2:Value1 list(2):Name2:Value1
list(3): Name3:Value3 list(3):Name3:Value3
By this (2) 由此(2)
Map<String, List<Item>> itemsByName = new HashMap<>();
for (Item m : list) {
if (!itemsByName.containsKey(m.getName())) {
ArrayList<Item> items = new ArrayList<>();
items.add(m);
itemsByName.put(m.getName(), items);
} else {
itemsByName.get(m.getName()).add(m);
}
}
I want to get: 我想得到:
MapKey(Name1): List{Name1:Value1, Name1:Value2} MapKey(Name1):列表{Name1:Value1,Name1:Value2}
MapKey(Name2): List{Name2:Value1} MapKey(Name2):列表{Name2:Value1}
MapKey(Name3): List{Name3:Value3} MapKey(Name3):列出{Name3:Value3}
How to rewrite code (2) using the stream() to get the same result? 如何使用stream()重写代码(2)以获得相同的结果?
You appear to be implementing the standard "group by" primitive. 您似乎正在实施标准的“分组依据”原语。 This is supported out-of-the-box by the Streams API: Streams API支持开箱即用:
Map<String, List<Item>> itemsByName =
list.stream().collect(Collectors.groupingBy(Item::getName));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.