nantitv
nantitv

Reputation: 3733

Convert ImmutableListMultimap to Map using Collectors.toMap

I would like to convert a ImmutableListMultimap<String, Character> to Map<String, List<Character>>. I used to do it in the non-stream way as follows

    void convertMultiMaptoList(ImmutableListMultimap<String, Character> reverseImmutableMultiMap) {
            Map<String, List<Character>> result = new TreeMap<>();
          for( Map.Entry<String, Character> entry: reverseImmutableMultiMap.entries()) {
              String key = entry.getKey();
              Character t = entry.getValue();
          result.computeIfAbsent(key, x-> new ArrayList<>()).add(t);
       }
       //reverseImmutableMultiMap.entries().stream().collect(Collectors.toMap)
}

I was wondering how to write the above same logic using java8 stream way (Collectors.toMap).

Please share your thoughts

Upvotes: 2

Views: 1059

Answers (2)

Eugene
Eugene

Reputation: 120968

Well there is already a asMap that you can use to make this easier:

    Builder<String, Character> builder = ImmutableListMultimap.builder();
    builder.put("12", 'c');
    builder.put("12", 'c');

    ImmutableListMultimap<String, Character> map = builder.build();

    Map<String, List<Character>> map2 = map.asMap()
            .entrySet()
            .stream()
            .collect(Collectors.toMap(Entry::getKey, e -> new ArrayList<>(e.getValue())));

If on the other hand you are OK with the return type of the asMap than it's a simple method call:

 ImmutableMap<String, Collection<Character>> asMap =  map.asMap();

Upvotes: 4

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22254

Map<String, List<Character>> result = reverseImmutableMultiMap.entries().stream()
    .collect(groupingBy(Entry::getKey, TreeMap::new, mapping(Entry::getValue, toList())));

The important detail is mapping. It will convert the collector (toList) so that it collects List<Character> instead of List<Entry<String, Character>>. According to the mapping function Entry::getValue

groupingBy will group all entries by the String key

toList will collect all values with same key to a list

Also, passing TreeMap::new as an argument to groupingBy will make sure you get this specific type of Map instead of the default HashMap

Upvotes: 1

Related Questions