在下面发布的代码中,我需要从HashMap中删除重复项(字母最高值保留在地图中),并在删除重复项后打印 k 最高值的键。我该怎么做呢?我尝试了HashSet,但我一无所知。
public ArrayList<String> mostOften(int k)
{
ArrayList<String> lista = new ArrayList<String>();
HashMap<String,Integer> temp = new HashMap<String, Integer>();
for(String it : wordList)
{
if(temp.containsKey(it))
temp.put(it, temp.get(it)+1);
else
temp.put(it, 1);
}
temp = sortByValues(temp);
Set<Integer> set = new HashSet<Integer>(temp.values());
System.out.println(set);
return lista;
}
private static HashMap sortByValues(HashMap map)
{
List list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator()
{
public int compare(Object o1, Object o2)
{
return ((Comparable)((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());
}
});
HashMap sortedHashMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();)
{
Map.Entry entry = (Map.Entry) it.next();
sortedHashMap.put(entry.getKey(), entry.getValue());
}
return sortedHashMap;
}
最佳答案
如果您尝试对单词进行频次计数,那么您将走错路。 Java 8做到了这一点更加轻松和整洁。
您需要这些进口
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
代码
public static void main(String[] args) {
printTopWords(Arrays.asList("Hello World Hello , Bye World".split(" ")), 2);
}
public static void printTopWords(List<String> words, int limit) {
// using the Stream API
words.stream()
// create a map of words with the count of those words
.collect(Collectors.groupingBy(w -> w, Collectors.counting()))
// take that map as a stream of entries
.entrySet().stream()
// sort them by count in reverse order
.sorted(Comparator.comparing(Map.Entry<String, Long>::getValue).reversed())
// limit the number to get top Strings
.limit(limit)
// keep just the key ie. drop the count.
.map(Map.Entry::getKey)
// print them
.forEach(System.out::println);
}
版画
Hello
World