【问题标题】:Sort HashMap with duplicate values对具有重复值的 HashMap 进行排序
【发布时间】: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 谢谢你的问题,我已经更新了问题,

标签: java sorting hashmap


【解决方案1】:

您正在使用TreeSet&lt;Integer&gt; sortedSet

根据定义,SETS 不允许重复。

这是一个示例,它按照您的预期按值排序,而不会丢失任何条目。

import java.util.*;

public class Test {

public static Map<String, Integer> sortByValueDesc(Map<String, Integer> map) {
    List<Map.Entry<String, Integer>> list = new LinkedList(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        @Override
        public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
            return o2.getValue().compareTo(o1.getValue());
        }
    });

    Map<String, Integer> result = new LinkedHashMap<>();
    for (Map.Entry<String, Integer> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}

    public static void main(String[] args) {

        HashMap<String, Integer> map = new HashMap<String, Integer>();

        map.put("item1", 1);
        map.put("item2", 2);
        map.put("item3", 1);
        map.put("item4", 7);
        map.put("item5", 3);
        map.put("item6", 4);

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println("Item is:" + entry.getKey() + " with value:"
                    + entry.getValue());
        }

        System.out.println("*******");

        Map<String,Integer> sortedMap = sortByValueDesc(map);

        for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
            System.out.println("Item is:" + entry.getKey() + " with value:"
                    + entry.getValue());
        }

    }

}

我得到的结果是(现在我检查你想要更大的值是第一个):

Item is:item4 with value:7
Item is:item2 with value:2
Item is:item3 with value:1
Item is:item1 with value:1
Item is:item6 with value:4
Item is:item5 with value:3
*******
Item is:item4 with value:7
Item is:item6 with value:4
Item is:item5 with value:3
Item is:item2 with value:2
Item is:item3 with value:1
Item is:item1 with value:1

为什么你在这里丢失一个元素是你的问题:

//HERE YOU ARE GETTING ALL THE VALUES
List<Integer> mapValues = new ArrayList<Integer>(tempMap.values());
HashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();

//YOU ARE INSERTING THE VALUES TO A TreeSet WHICH WILL REMOVE DUPLICATES
TreeSet<Integer> sortedSet = new TreeSet<Integer>(mapValues);

【讨论】:

  • 但它的重复值不是键。
  • @EmeEmertana 编辑我的答案也解决你为什么失去一个价值
  • 您的示例仍然无法按预期工作。它仍然以非降序返回值(应用您的 sortByValue 方法后,我得到了 10,10,10,10,3,4,3,10,10,6,1,1)。
  • @chao 请描述你是如何插入和排序的。我刚刚从 3 年前运行了这段代码,它适用于你评论提供的输入。 (10,10,10,10,6,4,3,3,1,1)
【解决方案2】:
public static void main(String[] args) {
    Set<Item> s = new TreeSet<Item>();
    s.add(new Item("item1", 5));
    s.add(new Item("item2", 1));
    s.add(new Item("item3", 7));
    s.add(new Item("item4", 1));

    for (Item it : s) {
        System.out.println("Item is:" + it.getName() + " with value:"
                + it.getValue());
    }

}

class Item implements Comparable<Item> {
    private Integer value;
    private String name;

    Item(String name, int val) {
        this.name = name;
        this.value = val;
    }

    // getters and sets

    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        if (obj == this)
            return true;
        if (obj.getClass() != getClass())
            return false;

        Item i = (Item) obj;
        if (i.getValue().equals(getValue())
                && i.getName().equals(getName()))
            return true;
        return false;

    }

    public int compareTo(Item o) {
        return getValue().compareTo(o.getValue());
    }

    public boolean equals(Object o) {
        return false;
    }
}

【讨论】:

    【解决方案3】:

    我相信你需要treeMap。它不允许重复,并将可比较作为键。如果可比较,则根据 compareTo() 进行排序,如果不是,则在构造函数中询问比较器。地图不允许重复

        Map<String,Integer> mymap = new TreeMap<String,Integer>();
        mymap.put("item1", 5);
        mymap.put("item2", 1);
        mymap.put("item3", 7);
        mymap.put("item4", 1);
    
    for(Map.Entry<String, Integer> entry: mymap.entrySet())
                System.out.println("Item is:" + entry.getKey() + " with value:" + 
                        entry.getValue());
    

    【讨论】:

      猜你喜欢
      • 2011-12-28
      • 2023-04-06
      • 2018-06-06
      • 2011-05-08
      • 1970-01-01
      • 2018-12-18
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多