作者:甘民涵 | 来源:互联网 | 2023-10-16 11:25
先上代码:importjava.io.*;importjava.util.*;publicclassMain{publicstaticvoidmain(Stri
先上代码:
import java. io. * ; import java. util. * ; public class Main { public static void main ( String [ ] args) throws IOException { HashMap < String , Integer > map&#61; new HashMap < > ( ) ; map. put ( "zhangsan" , 1 ) ; map. put ( "lisu" , 2 ) ; map. put ( "wangwu" , 3 ) ; List < Map. Entry < String , Integer > > list&#61; new ArrayList < > ( map. entrySet ( ) ) ; Collections . sort ( list, new Comparator < Map. Entry < String , Integer > > ( ) { &#64;Override public int compare ( Map. Entry < String , Integer > o1, Map. Entry < String , Integer > o2) { return o1. getValue ( ) - o2. getValue ( ) ; } } ) ; } }
具体步骤&#xff1a;
用list存储视图。 将list传入sort方法并重写比较器 注意数据类型也是要视图的形式。 如果这里的Key的类型也是Integer&#xff0c;重写的时候只需要把getValue()换成getKey&#xff08;&#xff09;就能实现对键排序。