1

To get the description frequencies of class objects:

public class Tag {  
    private int excerptID;
    private String description;
}

I use Collectors groupingBy + counting functions:

Map<String, Long> frequencyMap = rawTags.stream().map(Tag::getDescription).collect(Collectors.groupingBy(e -> e, Collectors.counting()));

But I want to return the result as a new object of the class

 public class Frequency {
    private String Description;
    private Long frequency;
    }

instead of Map<String, Long>. What is a simple way to do it?

krenkz
  • 484
  • 6
  • 15

1 Answers1

2

You can get entrySet of map and transform into Frequency class and collect as List.

rawTags.stream()
       .map(Tag::getDescription)
       .collect(Collectors.groupingBy(e -> e, Collectors.counting()))
       .entrySet()
       .stream()
       .map(e -> new Frequency(e.getKey(), e.getValue()))
       .collect(Collectors.toList());

Or using Collectors.collectingAndThen

rawTags.stream()
    .map(Tag::getDescription)
    .collect(Collectors.groupingBy(e -> e,
              Collectors.collectingAndThen(Collectors.toList(),
                                e -> new Frequency(e.get(0), Long.valueOf(e.size())))));
Eklavya
  • 17,618
  • 4
  • 28
  • 57
  • The second method with `Collectors.collectingAndThen` works very well, but in the first the last `map` gets underlined and throws message `The method map(( e) -> {}) is undefined for the type Set>`. – krenkz Sep 18 '20 at 10:54
  • @krenkz Can you check again? it works for me. When updating the answer I forgot to put `.stream()` after `entrySet()` maybe that is the issue. – Eklavya Sep 18 '20 at 11:03
  • 1
    sorry, my bad...I used the original version without `stream()`, it works perfectly well, thank you! – krenkz Sep 18 '20 at 11:05