Skip to content

Instantly share code, notes, and snippets.

@VijayKrishna
Created July 11, 2013 07:23
Show Gist options
  • Save VijayKrishna/5973268 to your computer and use it in GitHub Desktop.
Save VijayKrishna/5973268 to your computer and use it in GitHub Desktop.
This gist comprises of the code that i use to answer this SO question: http://stackoverflow.com/questions/17584008/find-most-common-value-from-hashmap-of-set-in-java
import java.util.*;
public class CommonMapSetValues {
public static void main(String[] args) {
CommonMapSetValues obj = new CommonMapSetValues();
obj.addKeyValue("abc", new String[] {"ax1","au2","au3"});
obj.addKeyValue("def", new String[] {"ax1","au6"});
obj.addKeyValue("ijk", new String[] {"ax1","au2"});
System.out.println(obj.toString());
System.out.println(obj.getFrequencyMap());
System.out.println(obj.getFrequencyMap().getCommon(2));
System.out.println(obj.getFrequencyMap().getCommon(3));
System.out.println(obj.getFrequencyMap().getCommon(4));
}
private Map<String, Set<String>> map;
public CommonMapSetValues() {
map = new HashMap<String, Set<String>>();
}
public void addKeyValue(String key, String[] valueArray) {
Set<String> valueSet;
if(map.containsKey(key)) {
valueSet = map.get(key);
} else {
valueSet = new HashSet<String>();
map.put(key, valueSet);
}
Collections.addAll(valueSet, valueArray);
}
FrequencyMap getFrequencyMap() {
Map<String, Integer> frequencies = new HashMap<String, Integer>();
for(String key : this.map.keySet()) {
for(String element : this.map.get(key)) {
int count;
if(frequencies.containsKey(element)) {
count = frequencies.get(element);
} else {
count = 1;
}
frequencies.put(element, count + 1);
}
}
return new FrequencyMap(frequencies);
}
@Override public String toString() {
return map.toString();
}
}
class FrequencyMap implements Comparator<String> {
Map<String, Integer> map;
public FrequencyMap(Map<String, Integer> map) {
this.map = map;
}
public int compare(String a, String b) {
if (map.get(a) >= map.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
public ArrayList<String> getCommon(int threshold) {
ArrayList<String> common = new ArrayList<String>();
for(String key : this.map.keySet()) {
if(this.map.get(key) >= threshold) {
common.add(key);
}
}
return common;
}
@Override public String toString() {
return this.map.toString();
}
}
{abc=[ax1, au3, au2], def=[ax1, au6], ijk=[ax1, au2]}
{ax1=4, au6=2, au3=2, au2=3}
[ax1, au6, au3, au2]
[ax1, au2]
[ax1]
[Finished in 0.1s]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment