java如何对Map进行排序

2022年6月9日10:06:11

Map排序(按key排序,按value排序)

主要分两种,按键排序、按值排序。 而且,按key排序主要用于TreeMap,而按value排序则对于Map的子类们都适用。

一、按键排序

按Key排序主要用于TreeMap,可以实现按照Key值的大小,在对象插入时直接插入到合适的位置,保持Map的顺序性。

来看TreeMap的构造函数:TreeMap(Comparator<? super K> comparator):构造一个新的、空的树映射,该映射根据给定比较器进行排序。

这里的比较器是key的比较器。所以定义比较器时用于比较的两个参数是Key的数据类型的对象。

实例代码如下:

publicclassMapSortTest{publicstaticvoidmain(String[] args){Map<String,String> stu=newTreeMap<>(newMyComparator());//传进来一个key的比较器对象来构造treemap
  stu.put("apple","55");
  stu.put("boy","32");
  stu.put("cat","22");
  stu.put("dog","12");
  stu.put("egg","11");//map的遍历:把key抽取出来用set存放,然后用迭代器遍历keyset,同时用map.get(KEY)获取key所对应的value。Set<String> keySet=stu.keySet();Iterator it=keySet.iterator();while(it.hasNext()){String next=(String)it.next();System.out.println(next+","+stu.get(next));}}}//定义key的比较器,比较算法根据第一个参数o1,小于、等于或者大于o2分别返回负整数、0或者正整数,来决定二者存放的先后位置:返回负数则o1在前,正数则o2在前。classMyComparatorimplementsComparator<String>{publicintcompare(String o1,String o2){return o1.compareTo(o2);}}

**

二、按值排序

与按值排序只使用TreeMap不同,按值排序由于其方法所用到的类型的统一性,所以能用于Map的所有子类。

主要用到的知识点有;

1:map.entrySet()将map里的每一个键值对取出来封装成一个Entry对象并存放到一个Set里面。

2:泛型Map.Entry<type1,type2> 因为Key-value对组成Entry对象,此处指明Entry对象中这两个成员的数据类型。

3:Collections.sort(List list, Comparator<? super T> c) 集合类的排序方法,通过自定义的比较器进行排序。这里的list存放的对象是entry对象。定义比较器对entry对象中的value属性进行比较。

实例代码如下:

publicclassMapSortTest{publicstaticvoidmain(String[] args){Map<String,String> stu=newTreeMap<>();//用TreeMap储存// Map<String,String> stu=new HashMap<>();//用HashMap储存

    stu.put("apple","55");
    stu.put("boy","32");
    stu.put("cat","22");
    stu.put("dog","12");
    stu.put("egg","11");//1:把map转换成entryset,再转换成保存Entry对象的list。List<Map.Entry<String,String>> entrys=newArrayList<>(stu.entrySet());//2:调用Collections.sort(list,comparator)方法把Entry-list排序Collections.sort(entrys,newMyComparator());//3:遍历排好序的Entry-list,可得到按顺序输出的结果for(Map.Entry<String,String> entry:entrys){System.out.println(entry.getKey()+","+entry.getValue());}}}//自定义Entry对象的比较器。每个Entry对象可通过getKey()、getValue()获得Key或Value用于比较。换言之:我们也可以通过Entry对象实现按Key排序。classMyComparatorimplementsComparator<Map.Entry>{publicintcompare(Map.Entry o1,Map.Entry o2){return((String)o1.getValue()).compareTo((String)o2.getValue());}}
  • 作者:朝上
  • 原文链接:https://blog.csdn.net/m0_51051154/article/details/120392110
    更新时间:2022年6月9日10:06:11 ,共 2132 字。