Java:按键和值对哈希图进行排序

时间:2018-10-31 10:31:28

标签: java sorting hashmap

我想通过键和值对哈希映射进行排序。目前,我已经按值对地图进行了排序,但是键包含要在不影响先前按值对地图进行排序的情况下进行排序的字符串?

按值排序后的地图

class Person(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.TextField(unique=False)

    def __init__(self, *args, **kwargs):
        # ... (do something) ...
        super(Person, self).__init__(*args, **kwargs)
        # ... (do something) ...

    def print_person_info(self):
        print(self.name)

我如何对地图进行排序

{Login to new=27, Failed login=27, Impossible=21}

我尝试先按值排序,然后按键排序,但未能实现所需的条件。

PS我对Java很陌生

编辑:添加了我从堆栈溢出中获取的排序功能

{Failed login =27, Login to new =27, Impossible =21}

4 个答案:

答案 0 :(得分:0)

您可以像下面这样编写自己的比较器-

class MapValueKeyComparator<K extends Comparable<? super K>, V extends Comparable<? super V>>
        implements Comparator<Map.Entry<K, V>> {

    public int compare(Map.Entry<K, V> a, Map.Entry<K, V> b) {
        int cmp1 = b.getValue().compareTo(a.getValue()); //can reverse a and b position for ascending/descending ordering
        if (cmp1 != 0) {
            return cmp1;
        } else {
            return a.getKey().compareTo(b.getKey()); //can reverse a and b position for ascending/descending ordering
        }
    }

}

将所有地图条目放入列表中并对其进行排序-

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

    map.put("Login to new", 27);
    map.put("Failed login", 27);
    map.put("Impossible", 21);

  List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
   Collections.sort(list, new MapValueKeyComparator<String, Integer>());

  for(Map.Entry<String, Integer> m : list){
     System.out.println(m);
  }

输出-

登录失败= 27 登录到new = 27 Impossible = 21

说明-MapValueKeyComparator对给定地图的键和值进行排序,其中先对值进行排序,然后对键进行排序。在主代码中,将所有映射条目都放在列表中,以便可以使用Java的Collections util类使用此比较器对它进行排序。

答案 1 :(得分:0)

您可以按照描述的方式对地图的内容进行排序;但是,输出将是一个列表,即一个排序的列表。然后,您需要处理该列表以获得所需的输出。

此代码应执行您想要的操作:

    Comparator<Entry<String, Integer>> byKeyThenByValue = Comparator.comparing(
            entry -> entry.getKey() + entry.getValue());

    List<Entry<String, Integer>> outList = mymap.entrySet().stream()
            .peek(entry -> System.out.println("K: " + entry.getKey() + "  v: " + entry.getValue()))
            .sorted(byKeyThenByValue)
            .collect(Collectors.toList());
    System.out.println(outList);

    Map<Object, Object> outMap = new LinkedHashMap<>();
    outList.forEach(entry -> outMap.put(entry.getKey(), entry.getValue()));
    System.out.println(outMap);

答案 2 :(得分:0)

做这样的事情

首先按键排序,然后按值排序

    Map<String, Integer> map=new HashMap<String, Integer>();
     map.put("Login to new", 27);
     map.put("Failed login", 27);
     map.put("Impossible", 21);

     List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(map.entrySet());

        //sort keys in ascending order
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
                return (e1.getKey()).compareTo(e2.getKey());
            }
        });

        //sort by values in descending order
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
                return (e2.getValue()).compareTo(e1.getValue());
            }
        });


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

输出

{Failed login=27, Login to new=27, Impossible=21}

答案 3 :(得分:0)

public static void main(String...strings) throws IOException {
        Map<String, String[]> map = new TreeMap<String, String[]>(){            
            @Override
            public String[] put(String key, String[] value){
                Arrays.sort(value);
                return super.put(key, value);
            }
        };

        map.put("Apple11", new String[]{"Zinc", "Iridium", "Apple"});
        map.put("Apple1", new String[]{"Xenon", "Zinc", "Brass"});

        for (Entry<String, String[]> entry : map.entrySet()) {
            System.out.println(entry.getKey()+"  ::  "+Arrays.toString(entry.getValue()));
        }
    }

输出::

Apple1  ::  [Brass, Xenon, Zinc]
Apple11  ::  [Apple, Iridium, Zinc]