Reputation: 295
Trying to figure out how can i use the new Java 8 feature .stream() in my code effectively.
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)
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(1): Name1:Value2
list(2): Name2:Value1
list(3): Name3:Value3
By this (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(Name2): List{Name2:Value1}
MapKey(Name3): List{Name3:Value3}
How to rewrite code (2) using the stream() to get the same result?
Upvotes: 3
Views: 734
Reputation: 1843
You appear to be implementing the standard "group by" primitive. This is supported out-of-the-box by the Streams API:
Map<String, List<Item>> itemsByName =
list.stream().collect(Collectors.groupingBy(Item::getName));
Upvotes: 5