简体   繁体   中英

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.

using Collectors.toMap:

Map<String, Transaction> transactions = transactions.stream()
        .collect(Collectors.toMap(Transaction::getID, Function.identity()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM