Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Guava's ImmutableSortedMap as a frequency map

Tags:

java

java-8

guava

I have a problem understanding how to use ImmutableSortedMap.toImmutableSortedMap(), when I want to create a frequency map. I know about Multiset (asked about that previously and got excellent help), but I don't want to use it this time, because it will require me to write a custom serializer to create a json representation that works for the consumers of said json.

The below code works, i.e. it creates the desired frequency map, sorted on key in ascending order, but it uses a temporary map, which I then use to create the ImmutableSortedMap. I would like to get rid of the temporary map. My attempts to use toImmutableSortedMap() collector method for this scenario failed to produce code that even compiled...

I am using Java 8 and Guava version 28.1

@Test
public void test() {
    Map<String, Long> intermediateMap = Stream.of("b", "a", "c", "b")
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    ImmutableSortedMap<String, Long> desiredMap = ImmutableSortedMap.copyOf(intermediateMap);

    System.out.println(desiredMap); // Outputs {a=1, b=2, c=1}, which is the desired state
}
like image 821
Eric Lilja Avatar asked Jan 26 '23 12:01

Eric Lilja


1 Answers

 Map<String, Long> result =
        Stream.of("b", "a", "c", "b")
              .collect(ImmutableSortedMap.toImmutableSortedMap(
                  Comparator.naturalOrder(),
                  Function.identity(),
                  x -> 1L,
                  Long::sum
              ));
like image 158
Eugene Avatar answered Jan 30 '23 04:01

Eugene