Reputation: 939
I have list of Inventory
:
class Inventory {
String refCode;
int min;
int max;
// getters and setters
}
refCode min max
------- ---- ---
DOUBLE 2 2
DOUBLE 2 2
TWIN 1 2
SINGLE 3 4
Now I wanted to group by using min
property so that my output would be like this:
Map<String, int> output;
{DOUBLE=2, TWIN=1, SINGLE=3}
Upvotes: 0
Views: 48
Reputation: 11042
You can simply use Collectors.toMap()
to achieve this:
Map<String, Integer> result = list.stream()
.collect(Collectors.toMap(Inventory::getRefCode, Inventory::getMin, (a, b) -> a));
This keeps the first value if you have multiple keys. If you want to keep the last one just use (a, b) -> b
instead of (a, b) -> a
.
If you need the items to be in the same order as the list just use a LinkedHashMap
:
Map<String, Integer> result = list.stream()
.collect(Collectors.toMap(Inventory::getRefCode, Inventory::getMin, (a, b) -> a, LinkedHashMap::new));
Upvotes: 3