I'm trying to find the top k frequent word in an input string. However, in my test case, it's printing out [Ljava.lang.String;@38af3868
even I tried to use the toString methods. What do I need to do to print out the string output instead of references? I should see strings as {"a","b"} here instead of references.
public class TopKFrequentWords {
public static void main(String[] args) {
TopKFrequentWords s = new TopKFrequentWords();
String [] e1 = {"a", "b", "c", "a", "b"};
String[] res = s.topKFrequent(e1,2);
System.out.print(res.toString()); //is not printing out strings
}
public String[] topKFrequent(String[] combo, int k) {
if (combo.length == 0) {
return new String[0];
}
Map<String, Integer> freqMap = getFreqMap(combo);
PriorityQueue<Map.Entry<String, Integer>> minHeap = new PriorityQueue<>(k,
new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
//compareTo compares map e1's fre with e2's freq
return e1.getValue().compareTo(e2.getValue());
}
});
// .entry set() returns a collection view of the mappings contained in the map
for (Map.Entry<String, Integer> entry: freqMap.entrySet()) {
if (minHeap.size() < k) {
minHeap.offer(entry);
} else if (entry.getValue() > minHeap.peek().getValue()) {
minHeap.poll();
minHeap.offer(entry);
}
}
return freqArray(minHeap);
}
private Map<String, Integer> getFreqMap(String[] combo) {
Map<String, Integer> freqMap = new HashMap<>();
//for s in combo; for i = 0; i< combo.length(), i++
for (String s: combo) {
Integer freq = freqMap.get(s);
if (freq == null) {
freqMap.put(s,1);
} else {
freqMap.put(s, freq + 1);
}
}
return freqMap;
}
private String[] freqArray(PriorityQueue<Map.Entry<String, Integer>> minHeap) {
String[] res = new String[minHeap.size()];
for (int i = 0; i < minHeap.size(); i++) {
res[i] = minHeap.poll().getKey();
}
return res;
}
}