1.大顶堆
PriorityQueue<Integer> queue = new PriorityQueue<Integer>(
// 匿名内部类
// new Comparator<Integer>() {
// public int compare(Integer num1, Integer num2) {
// return num2 - num1;
// }
// }
//简写为下面一行
(Integer num1, Integer num2)->{return num2 - num1;}
);
2.二维数组按照第一维度排序
Arrays.sort(intervals,
new Comparator<int []>() {
@Override
public int compare(int[] a,int[] b) {
if(a[0]==b[0])
return a[1]-b[1];
return a[0]-b[0];
}});
//简写为下面一行
//给intervals排序
Arrays.sort(intervals,
(int[] a,int[] b)-> {
if(a[0]==b[0])
return a[1]-b[1];
return a[0]-b[0];
});
3.Integer数组的降序排列
public class Main {
public static void main(String[] args) {
Integer[] arr={9,8,7,6,5,4,3,2,1};
// Comparator cmp=new CMP();
// Arrays.sort(arr,cmp);
//下面这行代码用于取代上面的两行
Arrays.sort(arr,(o1,o2)->o2-o1);
for(int i:arr){
System.out.println(i);
}
}
}
class CMP implements Comparator<Integer>{
@Override //可以去掉。作用是检查下面的方法名是不是父类中所有的
public int compare(Integer a,Integer b){
// 两种都可以,升序排序的话反过来就行
// return a-b<0?1:-1;
return b-a;
}
}
4.list的降序排列
ArrayList arr = new ArrayList();
arr.add(11);
arr.add(33);
arr.add(22);
Collections.sort(arr, new Comparator() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
5.今天是让TreeMap按照VALUE排序,默认是按照Key从大到小排序
// 1 定义map
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
// 2 给Map添加数据据
map.put(1,10);
map.put(2,2);
map.put(3,30);
// 3 定义listmap,按照TreeMap的value排个序
List<Map.Entry<Integer,Integer>> listmap = new ArrayList<Map.Entry<Integer,Integer>>(map.entrySet());
/*
//写法一
Collections.sort(listmap,new Comparator<Map.Entry<Integer,Integer>>() {
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
*/
//写法二
Collections.sort(listmap,(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2)->
o2.getValue().compareTo(o1.getValue()));
// 4 输出
for(Map.Entry <Integer,Integer> e:listmap){
System.out.print(e.getKey()+" ");
}
6.这次是TreeMap按照key从大到小的顺序
// 1 定义map
TreeMap<Integer, Integer> mapKey = new TreeMap<Integer, Integer>((o1,o2)->(o1-o2));
mapKey.put(1,1);
mapKey.put(2,2);
mapKey.put(3,3);
Set<Integer> integers = mapKey.keySet();
for(int n:integers){
System.out.println(n+" "+mapKey.get(n));
}
参考链接: