Map集合排序——根据value对key进行排序
首先来看看Map集合获取元素的三种常见方法keySet()、values()、entrySet()
values():返回map集合的所有value的Collection集合(于集合中无序存放)
1 import java.util.*; 2 3 public class Main{ 4 public static void main(String[] args){ 5 Map<String, String> map = new HashMap<String, String>(); //构建键值对为<String, String>的Map集合 6 map.put("a", "aaa"); 7 map.put("b", "bbb"); 8 map.put("c", "ccc"); 9 10 Collection<String> collection = map.values(); //获取map集合的所有value的Collection集合(于集合中无序存放) 11 System.out.println(collection); 12 } 13 } 14 15 /** 16 * 运行结果 17 * [bbb, ccc, aaa] 18 */
keySet():返回map集合的所有键的Set集合(于Set集合中无序存放)
通过迭代取出所有key,再利用get()方法获取value, for(类型 元素: 集合) 的本质是获取集合的迭代器进行迭代
1 import java.util.*; 2 3 public class Main{ 4 public static void main(String[] args){ 5 Map<String, String> map = new HashMap<String, String>(); //构建键值对为<String, String>的Map集合 6 map.put("a", "aaa"); 7 map.put("b", "bbb"); 8 map.put("c", "ccc"); 9 10 Set<String> keySet = map.keySet(); //获取map集合的所有键的Set集合(于Set集合中无序存放) 11 Iterator<String> iter = keySet.iterator(); //获取keySet集合的迭代器 12 while(iter.hasNext()){ 13 String key = iter.next(); 14 String value = map.get(key); 15 System.out.println("key:" + key + "-->value:" + value); 16 } 17 /* 18 for(String key: keySet){ 19 String value = map.get(key); 20 System.out.println("key:" + key + "-->value:" + value); 21 } 22 */ 23 } 24 } 25 26 /** 27 * 运行结果 28 * key:b-->value:bbb 29 * key:c-->value:ccc 30 * key:a-->value:aaa 31 */
entrySet():返回map集合的所有"映射"的Set集合,这里规范每个"映射"的类型为Map.Entry(于Set集合中无序存放)通过迭代取出所有的“映射”,再利用getKey()、getValue()方法获取相应键、值
1 import java.util.*; 2 3 public class Main{ 4 public static void main(String[] args){ 5 Map<String, String> map = new HashMap<String, String>(); //构建键值对为<String, String>的Map集合 6 map.put("a", "aaa"); 7 map.put("b", "bbb"); 8 map.put("c", "ccc"); 9 10 Set<Map.Entry<String, String>> entrySet = map.entrySet(); //获取map集合的所有"映射"的Set集合,这里规范每个映射的类型为Map.Entry<K, V>(于Set集合中无序存放) 11 Iterator<Map.Entry<String, String>> iter = entrySet.iterator(); //获取entrySet集合的迭代器,Map.Entry<K, V>为迭代元素的类型 12 while(iter.hasNext()){ 13 Map.Entry<String, String> item = iter.next(); 14 String key = item.getKey(); 15 String value = item.getValue(); 16 System.out.println("key:" + key + "-->value:" + value); 17 } 18 /* 19 for(Map.Entry<String, String> item: entrySet){ 20 String key = item.getKey(); 21 String value = item.getValue(); 22 System.out.println("key:" + key + "-->value:" + value); 23 } 24 */ 25 } 26 } 27 28 /** 29 * 运行结果 30 * key:b-->value:bbb 31 * key:c-->value:ccc 32 * key:a-->value:aaa 33 */
有以上方法作为基础,那么我们很容易想到对HashMap进行排序的两种方法
1.通过keySet()获取Map集合的所有键的Set集合,由List集合获取其中所有元素,通过比较器对元素为键的List集合进行排序
2.通过entrySet()获取Map集合所有映射的Set集合,由List集合获取其中所有元素,通过比较器对元素为"映射"List集合进行排序
通过对比较器compare方法的Override,两者还可以实现利用value进行排序。
1 import java.util.*; 2 3 public class DescKeyComparator implements Comparator<String>{ 4 public static void main(String[] args){ 5 Map<String, String> map = new HashMap<String, String>(); //构建键值对为<String, String>的Map集合 6 map.put("a", "aaa"); 7 map.put("b", "bbb"); 8 map.put("c", "ccc"); 9 10 Set<String> entrySet = map.keySet(); //获取map集合的所有键的Set集合(于Set集合中无序存放) 11 List<String> list = new ArrayList<String>(entrySet); //新建List集合获取Set集合的所有元素(键对象)(顺序与Set集合一样) 12 /** 13 * 接下来的排序是list的专长了 14 * 通过“比较器(DescKeyComparator)”,对list进行排序 15 */ 16 Collections.sort(list, new DescKeyComparator()); 17 /* 18 Collections.sort(list); //String实现了Comparable,默认升序排列 19 */ 20 Iterator<String> iter = list.iterator(); //获取List集合的迭代器,String为迭代元素的类型 21 while(iter.hasNext()){ 22 String key = iter.next(); 23 String value = map.get(key); 24 System.out.println("key:" + key + "-->value:" + value); 25 } 26 /* 27 for(Map.Entry<String, String> item: list){ 28 String key = iter.next(); 29 String value = map.get(key); 30 System.out.println("key:" + key + "-->value:" + value); 31 } 32 */ 33 } 34 35 @Override 36 public int compare(String key1, String key2){ 37 return key2.compareTo(key1); //降序排序; String作为api提供的类,实现了Comparable的compareTo方法被设计成小于、等于、大于分别返回负数、零、正数 38 } 39 } 40 41 /** 42 * 运行结果 43 * key:c-->value:ccc 44 * key:b-->value:bbb 45 * key:a-->value:aaa 46 */
1 import java.util.*; 2 3 public class AscKeyComparator implements Comparator<Map.Entry<String, String>>{ 4 public static void main(String[] args){ 5 Map<String, String> map = new HashMap<String, String>(); //构建键值对为<String, String>的Map集合 6 map.put("a", "aaa"); 7 map.put("b", "bbb"); 8 map.put("c", "ccc"); 9 10 Set<Map.Entry<String, String>> entrySet = map.entrySet(); //获取map集合的所有"映射"的Set集合,这里规范每个映射的类型为Map.Entry<K, V>(于Set集合中无序存放) 11 List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(entrySet); //新建List集合获取Set集合的所有元素("映射"对象)(顺序与Set集合一样) 12 /** 13 * 接下来的排序是list的专长了 14 * 通过“比较器(AscKeyComparator)”,对list进行排序 15 */ 16 Collections.sort(list, new AscKeyComparator()); 17 18 Iterator<Map.Entry<String, String>> iter = list.iterator(); //获取List集合的迭代器,Map.Entry<K, V>为迭代元素的类型 19 while(iter.hasNext()){ 20 Map.Entry<String, String> item = iter.next(); 21 String key = item.getKey(); 22 String value = item.getValue(); 23 System.out.println("key:" + key + "-->value:" + value); 24 } 25 /* 26 for(Map.Entry<String, String> item: list){ 27 String key = item.getKey(); 28 String value = item.getValue(); 29 System.out.println("key:" + key + "-->value:" + value); 30 } 31 */ 32 } 33 34 @Override 35 public int compare(Map.Entry<String, String> item1, Map.Entry<String, String> item2){ 36 return item1.getKey().compareTo(item2.getKey()); //升序排序 37 } 38 } 39 40 /** 41 * 运行结果 42 * key:a-->value:aaa 43 * key:b-->value:bbb 44 * key:c-->value:ccc 45 */
以下是我的练习小Demo,HashMap键值排序
需要注意的是:
Comparator和Comparable的区别
Comparable:自己(this)和别人(参数)比较,自己需要实现Comparable接口,重写比较的规则compareTo方法
Comparator:相当于找一个第三方的裁判,比较两个
Comparator的排序规则:o1-o2:升序
package cn.kgc.kb03.homework10; /** * @author:? * @date:2019/9/5 * @aim: 统计同学的学号,姓名,并插入map中 *要求:遍历所有同学,原本乱序,按学号排序 */ public class Student implements Comparable { private int num; private String name; public Student(){ } public Student(int num, String name){ this.num=num; this.name=name; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } //.toString 方法是将对象及其他转换成字符串的形式表达 //这个方法重新定义toString ,是返回值是自身期望的。 public String toString(){ return "学号:"+num+" 姓名:"+name; } //重写compareTo方法 public int compareTo(Object obj){ Student student=(Student)obj; if(this.num==student.num){ return 0; }else if(this.num>student.getNum()){ return 1; }else { return -1; } } }
package cn.kgc.kb03.homework10; import java.util.*; /** * @author:? * @date:2019/9/5 * @aim:按学号进行升序排列 */ //HashMap本身是不可以排序的,但其子类LinkedHashMap是有序的 //可以利用LinkedHashMap+List+Collections工具实现HashMap排序 public class HashMapSort { public static void main(String[] args) { //创建HashMap集合 HashMap<Integer, Student> hashMap = new HashMap<>(); //把序号和学员对象按照键值对的方式存储在HashMap中 hashMap.put(1, new Student(1, "A")); hashMap.put(2, new Student(3, "B")); hashMap.put(3, new Student(2, "C")); hashMap.put(4, new Student(5, "D")); hashMap.put(5, new Student(4, "E")); //调用sortHashMap()排序并返回新的集合 HashMap<Integer,Student> sort = sortHashMap(hashMap); System.out.println(sort); } private static HashMap<Integer, Student> sortHashMap(HashMap<Integer, Student> map) { //从HashMap中恢复entry集合,得到全部的键值对集合 Set<Map.Entry<Integer,Student>> entries= map.entrySet(); //将Set集合转为List集合,为了使用工具类的排序方法 List<Map.Entry<Integer,Student>> list= new ArrayList<Map.Entry<Integer,Student>>(entries); //使用Collections工具类对list进行排序 //Collections.sort()是一个内置方法,仅排序值的列表。它在Collections类中重载。 Collections.sort(list, new Comparator<Map.Entry<Integer, Student>>() { @Override public int compare(Map.Entry<Integer, Student> o1, Map.Entry<Integer, Student> o2) { //按照学号升序排序 return o1.getValue().getNum()-o2.getValue().getNum(); //return o1.getValue().compareTo(o2.getValue()); } }); //创建一个HashMap的子类LinkedHashMap集合 LinkedHashMap<Integer, Student> linkedHashMap= new LinkedHashMap<>(); //将list中的数据存入LinkedHashMap中 for(Map.Entry<Integer,Student> entry:list){ linkedHashMap.put(entry.getKey(),entry.getValue()); } return linkedHashMap; } }