【发布时间】:2012-09-26 03:15:09
【问题描述】:
您好,我正在使用以下代码对我的 HashMap 进行排序,它对地图进行正确排序但不计算重复值,
Map<String, Integer> mymap = new HashMap<String, Integer>();
mymap.put("item1", 5);
mymap.put("item2", 1);
mymap.put("item3", 7);
mymap.put("item4", 1);
Map<String, Integer> tempMap = new HashMap<String, Integer>();
for (String wsState : mymap.keySet()) {
tempMap.put(wsState, mymap.get(wsState));
}
List<String> mapKeys = new ArrayList<String>(tempMap.keySet());
List<Integer> mapValues = new ArrayList<Integer>(tempMap.values());
HashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
TreeSet<Integer> sortedSet = new TreeSet<Integer>(mapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
for (int i = 0; i < size; i++) {
sortedMap.put(mapKeys.get(mapValues.indexOf(sortedArray[i])),
(Integer) sortedArray[i]);
}
for (Map.Entry<String, Integer> entry : mymap.entrySet())
System.out.println("Item is:" + entry.getKey() + " with value:"
+ entry.getValue());
System.out.println("***");
for (Map.Entry<String, Integer> entry : sortedMap.entrySet())
System.out.println("Item is:" + entry.getKey() + " with value:"
+ entry.getValue());
结果如下(第4项没有显示,因为它的值与第2项相同!!!):
Item is:item4 with value:1
Item is:item2 with value:1
Item is:item3 with value:7
Item is:item1 with value:5
***
Item is:item2 with value:1
Item is:item1 with value:5
Item is:item3 with value:7
它是一个HashMap,需要按值排序。 预期输出为:
Item is:item3 with value:7
Item is:item1 with value:5
Item is:item2 with value:1
Item is:item4 with value:1
或
Item is:item2 with value:1
Item is:item4 with value:1
Item is:item1 with value:5
Item is:item3 with value:7
【问题讨论】:
-
不确定您要做什么,按键排序?价值?计算重复?什么?
-
我有一个HashMap,需要按Value排序。
-
ok,然后创建treeMap并放入:value->key,它会自动排序然后创建hashMap并从treeMap中读取所有值并放入hashmap,不需要任何逻辑
-
您输入的预期输出是什么?那么就清楚了
-
@elbek 谢谢你的问题,我已经更新了问题,