二维数组自定义排序
Arrays.sort(intervals,new Comparator<int[]>() {
@Override
public int compare(int[]a,int[]b)
{
return a[0]==b[0]?b[1]-a[1]:a[0]-b[0];
} });
Treemap自定义排序
Map map = new TreeMap();
map.put("a", "ddddd");
map.put("c", "bbbbb");
map.put("d", "aaaaa");
map.put("b", "ccccc");
List<Map.Entry> list = new ArrayList<>(map.entrySet());
Collections.sort(list,new Comparator<>() {
public int compare(Map.Entry o1, Map.Entry o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
for(Map.Entry mapping:list){
System.out.println(mapping.getKey()+":"+mapping.getValue());
}
priorityqueue自定义排序
两种方式:可以对自己的定义的对象先重写Comparable接口然后自己写排序方式
class Status implements Comparable<Status> {
int val;
ListNode ptr;
public Status(int val,ListNode ptr)
{
this.val=val;
this.ptr=ptr;
}
public int compareTo(Status s2)
{
return ptr.val-s2.val;
}
}
PriorityQueue<Status>queue=new PriorityQueue<Status>();
public ListNode mergeKLists(ListNode[] lists) {
for(ListNode node:lists)
if (node != null) {
queue.offer(new Status(node.val,node));
}
方式二: 对priorityqueue排序:
PriorityQueue<int[]> queue = new PriorityQueue<int[]>(new Comparator<int[]>() {
public int compare(int[] m, int[] n) {
return m[1] - n[1];
}
});
|