【发布时间】:2016-03-17 23:43:21
【问题描述】:
在我在下面发布的代码中,我需要从 HashMap 中删除重复项(按字母顺序排列的最高值会保留在地图中)并在重复项被删除。我该怎么做呢?我尝试过使用 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;
}
【问题讨论】:
-
您能说得更具体些吗?您的地图中包含什么?
-
HashMap按设计无序。为什么不使用设计为像TreeMap这样排序的集合? -
定义中说,key是字符串,value是整数。
-
在那里查看我的答案:stackoverflow.com/questions/34233528/… 它反转值和键并按值排序
-
@PeterLawrey 因为我需要它按值排序,而不是按键排序。