Modifying the returned Map value type with collectors.groupingBy in Java stream

Rajkumar Natarajan :

I have below the class definition of Entry -

public class Entry {
    private String key;
    private String Value;
    // getters and setters
    // equals hashcode toString
}

I got List of Entry objects from database. I want to group them based on key and values of the result Map should be Set<value>.

I tried and end up with the below code.

Map<String, Set<Entry>> groupedEntries =  
        entryList.findAll()
                 .stream()
                 .collect(Collectors.groupingBy(ek -> ek.getKey().toLowerCase(), Collectors.toSet()));

The problem with this code is the result type is Map<String, Set<Entry>> but I want to be Map<String, Set<String>>.

is it possible to do this in single collect?

Ousmane D. :

use the mapping collector:

.collect(Collectors.groupingBy(ek -> ek.getKey().toLowerCase(), 
                  Collectors.mapping(Entry::getValue, Collector.toSet())));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=74436&siteId=1