美文网首页
用HashMap<>()排序

用HashMap<>()排序

作者: cmeizu | 来源:发表于2019-12-02 09:37 被阅读0次

很多场景下我们都要用到集合操作,同时要求我们按照一定的规则排序

public static void main(String[] args) {
        Map<Integer, Character> map = new HashMap<>();
        map.put(1, 'a');
        map.put(2, 'b');
        map.put(3, 'c');
        map.put(4, 'c');
        map.put(5, 'f');
        map.put(6, 'e');
        map.put(7, 'd');

        List<Map.Entry<Integer, Character>> list = new ArrayList<>(map.entrySet());
        list.sort(((o1, o2) -> o2.getValue() - o1.getValue()));
        list.forEach(e->{
            System.out.println(e.getKey() + "---" + e.getValue());
        });
    }
  • 这是按照值排序,当然也可以按照key,当然条件不止一个,可以添加多个条件做相应的判断.
  • 思路是先将其转化为list集合,再用比较器排序.

相关文章

网友评论

      本文标题:用HashMap<>()排序

      本文链接:https://www.haomeiwen.com/subject/lqdxgctx.html