Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java create Map of single value using stream collector groupingBy

I know the groupingBy return a Map<K,List<V>>. But If I know that each key has a unique value, how do I get a Map whose value is V instead of List<V>?

For example:

Map<String, Transaction> transactions =
transactions.stream().collect(groupingBy(Transaction::getID));

where ID is unique.

like image 411
Cosaic Avatar asked Aug 06 '18 19:08

Cosaic


1 Answers

using Collectors.toMap:

Map<String, Transaction> transactions = transactions.stream()
        .collect(Collectors.toMap(Transaction::getID, Function.identity()));
like image 73
Patrick Parker Avatar answered Oct 12 '22 13:10

Patrick Parker