思路:使用集合的sort方法,新建一个Comparator接口,泛型是<String>,重写里面的compare方法。
package jiang.com;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;public class Practice4 {public static void main(String[] args) {List<String> list = Arrays.asList("adafafafaf.txt","Afihfiafhai.xlsx","dajfjakfakjfafja.csv","1.psd","cs.exe");list.sort(new Comparator<String>() {@Overridepublic int compare(String o1, String o2) {return -o1.length()+o2.length();}});System.out.println(list);}
}
运行结果:
扩充:点击Comparator,查看接口内部:发现加了@FunctionalInterface,说明可以使用箭头函数,直接使用箭头函数就能表示Comparator接口以及它的comparator方法。
使用箭头函数的代码:直接在()写入参,然后在->{}的{}中写处理逻辑即可。
package jiang.com;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;public class Practice4 {public static void main(String[] args) {List<String> list = Arrays.asList("adafafafaf.txt","Afihfiafhai.xlsx","dajfjakfakjfafja.csv","1.psd","cs.exe");list.sort((o1, o2) -> {return -o1.length()+o2.length();});System.out.println(list);}
}