如何对HashMap中的元素进行排序

如题所述

HashMap是无序的集合,对里面的元素进行排序,需要借助其他有序的集合

    传统的思路:   把每一个HashMap的键值对作为一个Entry 存入到ArrayList<Entry>里.  然后对ArrayList进行排序.

    Java8新思路: 利用流对集合进行处理,非常强大, 如果配合上Lambda表达式, 就是简洁且强大.

参考代码

import java.util.HashMap;
//java8 流处理
public class Demo1 {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("lucy", 76);
map.put("tom", 92);
map.put("jack", 86);
// 按照 Key (名字)进行排序 ,并打印
map.entrySet().stream().sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey())).forEach(System.out::println);
System.out.println("-------分割线----------");
// 按照value(分数) 进行排序,并打印
map.entrySet().stream().sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue())).forEach(System.out::println);

}
}

温馨提示:答案为网友推荐,仅供参考
相似回答