Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-8

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?

like image 321
Rajkumar Natarajan Avatar asked Dec 23 '22 05:12

Rajkumar Natarajan


1 Answers

use the mapping collector:

.collect(Collectors.groupingBy(ek -> ek.getKey().toLowerCase(), 
                  Collectors.mapping(Entry::getValue, Collector.toSet())));
like image 177
Ousmane D. Avatar answered Jan 26 '23 00:01

Ousmane D.