user5394162
user5394162

Reputation: 9

java guava multimap output in particular format

I have the below MultiMap:

Multimap<String, Integer> mm = ArrayListMultimap.create();

mm.put("A", 10);
mm.put("B", 0);
mm.put("C", 0);
mm.put("A", 0);
mm.put("B", 11);
mm.put("C", 0);         
mm.put("A", 0);
mm.put("B", 0);             
mm.put("C", 5);     
mm.put("A", 4);
mm.put("B", 0);
mm.put("C", 0);     
mm.put("A", 0);
mm.put("B", 6);
mm.put("C", 0);     
mm.put("A", 0);
mm.put("B", 0);             
mm.put("C", 8);     
mm.put("A", 2);
mm.put("B", 0);
mm.put("C", 0);     
mm.put("A", 0);
mm.put("B", 0);
mm.put("C", 0);     
mm.put("A", 0);
mm.put("B", 0);             
mm.put("C", 7);

Set<String> keys = mm.keySet();
for (String key : keys) {           
    System.out.println("Key = " + key);
        System.out.println("Values = " + mm.get(key));          
}

I get the following output:

Key = A
Values = [10, 0, 0, 4, 0, 0, 2, 0, 0]
Key = B
Values = [0, 11, 0, 0, 6, 0, 0, 0, 0]
Key = C
Values = [0, 0, 5, 0, 0, 8, 0, 0, 7]

But I need the output in the format:

Key = A
Values = [10, 4, 2]
Key = B
Values = [11, 6, 0]
Key = C
Values = [5, 8, 7]

Upvotes: 0

Views: 150

Answers (2)

Mateusz Korwel
Mateusz Korwel

Reputation: 1148

You should use HashMultimap instead of ArrayListMultimap

Multimap<String, Integer> mm = HashMultimap.create();

Or if HashMultimap is not enough for you, you can check the value before putting it into the multimap.

if(!mm.containsValue(10)){
    mm.put("A", 10);
}

Upvotes: 1

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298898

Your use case could be solved easier with a Multiset, not a Multimap. First write a helper method:

static <T> void  addNTimes(Multiset<T> multiset, T item, int n) {
    multiset.addAll(Collections.nCopies(item, n));
}

Now you can rewrite your code:

Multiset<String> mm = HashMultiset.create();

addNTimes(mm, "A", 10);
addNTimes(mm, "B", 0);
addNTimes(mm, "C", 0);
addNTimes(mm, "A", 0);
addNTimes(mm, "B", 11);
addNTimes(mm, "C", 0);


Set<Entry<String>> keys = mm.entrySet();
for (Entry<String> entry : keys) {
    System.out.println("Key = " + entry.getElement());
    System.out.println("Values = " + entry.getCount());
}

Upvotes: 0

Related Questions