Search code examples
javacountguavamultimap

Count duplicate values in Multimap


I have Multimap. Example:

00254=[00255, 2074E, 2074E, 2074E, 2074E, 2074E, 2074E, 00010, 00010, 00010, 0006, 0006, 0006, 00010, R01018, R01018, 0006, 0006, R01018, R01018, R01018, 12062, S2202962, S2202962, R01018, 12062, 20466, 12062, 20466, 22636, 20466, 20466, 22636, 22636, 22636, 22636, 22636, 22636, 22636, 22636, 00255, 2074E, 2074E, 2074E, 2074E, 2074E]
00256=[00257, 2074E, 2074E, 2074E, 2074E, 00010, 2074E, 2074E, 0006, 00010, 00010, 00010, 0006, 0006, 0006, R01018, R01018, 0006, R01018, R01018, R01018, 12062, S2202962, S2202962, R01018, 12062, 20466, 12062, 20466, 20466, 20466, 22636, 22636, 22636, 22636, 22636, 22636, 22636, 22636, 22636, 00257, 2074E, 2074E, 2074E, 2074E, 00010]

I want to get the number of value including duplicate value.

  • 00254=[00255:2, 2074E:11, 00010:4, 0006:5, R01018:6, ...]
  • 00256=[00257:2, 2074E:10, 00010:5, 0006:5, R01018:7, ...]

Is it possible to get duplicate number?

Thanks.


Solution

  • Solution using Java 8 Stream to get the occurrence for a specific value, simply get the Collection for a value, then group on the value and count (using the Collectors function) to get a Map<String, Long> :

    Multimap<Integer, String> maps =  ArrayListMultimap.create();
    maps.put(1, "foo");
    maps.put(1, "bar");
    maps.put(1, "foo");
    maps.put(2, "Hello");
    maps.put(2, "foo");
    maps.put(2, "World");
    maps.put(2, "World");
    
    Here is the idea to print the occurences per value :
    
    maps.keySet().stream() //Iterate the `keys`
                .map(i -> i + " : " +  //For each key
                            maps.get(i).stream() //stream the values.
                                .collect( //Group and count
                                        Collectors.groupingBy(
                                                Function.identity(), 
                                                Collectors.counting()
                                        )
                                )
                )
                .forEach(System.out::println);
    

    1 : {bar=1, foo=2}

    2 : {Hello=1, foo=1, World=2}

    This will generate a String, I let you adapt for your need.