Counting values of element values inside a list inside a hash <String, List <String>>
I have a hash structure hash_feat <String, List<String>>, where my keys are Years , and in the values list contains a list of different terms.
I already have my hash, so that all elements from a certain key are in the same list for this key, for example:
<1997> <A,B,C,A,A,A,B,C,C,E>
<2003> <C,C,C,A,B,A,D,D,D,A>
<2004> <A,C,C,X,X,A,K,T,T,T>
I would like to have a count for each item. For 1997, A: 4, B: 2, C: 3, E: 1, etc., etc. For other keys .
I am trying to come up with this in order to use this “count” for later displaying on a figure, where I can visualize the highest values for each element in the graph. This is probably not the smartest way, so any advice here is also welcome. The idea is to have a count of each item in my list so that I can manipulate / use in other methods.
Does anyone have any good advice on doing this in a reasonable way?
Here's a “simple” solution for Java 8:
import static java.util.stream.Collectors.*;
Map<String, Map<String, Long>> props =
map.entrySet().stream().collect(toMap(Map.Entry::getKey,
e -> e.getValue().stream().collect(groupingBy(String::toString, counting()))));
This will give you a map of years on a key map for counting.
Eclipse Collections BagMultimap, . MutableBagMultimap .
MutableBagMultimap<String, String> multimap = Multimaps.mutable.bag.empty();
multimap.putAll("1997", Lists.mutable.with("A","B","C","A","A","A","B","C","C","E"));
multimap.putAll("2003", Lists.mutable.with("C","C","C","A","B","A","D","D","D","A"));
multimap.putAll("2004", Lists.mutable.with("A","C","C","X","X","A","K","T","T","T"));
Assert.assertEquals(4, multimap.get("1997").occurrencesOf("A"));
Assert.assertEquals(2, multimap.get("1997").occurrencesOf("B"));
Assert.assertEquals(3, multimap.get("1997").occurrencesOf("C"));
Assert.assertEquals(1, multimap.get("1997").occurrencesOf("E"));
multimap forEachKeyMultivalues toStringOfItemToCount.
multimap.forEachKeyMultiValues((key, values) ->
System.out.println("<" + key + "> " + ((Bag<String>)values).toStringOfItemToCount()));
:
<1997> {E=1, A=4, B=2, C=3}
<2004> {T=3, A=2, C=2, X=2, K=1}
<2003> {D=3, A=3, B=1, C=3}
, forEachWithOccurrences, .
multimap.forEachKey(key -> {
System.out.print(key + " ");
multimap.get(key).forEachWithOccurrences((value, occurrences) ->
System.out.print(value + ":" + occurrences + " "));
System.out.println();
});
:
1997 E:1 A:4 B:2 C:3
2004 T:3 A:2 C:2 X:2 K:1
2003 D:3 A:3 B:1 C:3
, topOccurrences, , .
multimap.forEachKey(key -> {
System.out.print(key + " ");
MutableBag<String> bag = multimap.get(key);
bag.topOccurrences(bag.sizeDistinct())
.each(pair ->
System.out.print(pair.getOne() + ":" + pair.getTwo() + " "));
System.out.println();
});
:
1997 A:4 C:3 B:2 E:1
2004 T:3 A:2 C:2 X:2 K:1
2003 D:3 A:3 C:3 B:1
: Eclipse