升序与降序
升序与降序
Comaparator接口用于实现排序,通常作为排序的参数输入
Lambda表达式允许通过表达式来代替功能接口功能
Lambda表达式的基本语法: (parameters) -> expression 或 (parameters) ->{ statements; }
//数组升序
int[] nums = {4, 3, 5, 2, 6, 1,7};
Arrays.sort(nums);
System.out.print(Arrays.toString(nums));
Integer[] nums = {4, 3, 5, 2, 6, 1,7};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
//数组降序
// (a,b)->b-a是Lambda 表达式,如果要降序排列,在sort后面传入一个Comparator接口即可,下面我使用的是lambda表达式,如果是a-b表示升序,b-a表示降序
int[] nums = {4, 3, 5, 2, 6, 1,7};
Integer[] numss = Arrays.stream(nums).boxed().toArray(Integer[]::new);//int[]转Integer[]
Arrays.sort(numss, (a,b)->b-a); //降序,lambda表达式
Arrays.sort(numss, (a,b)->b-a); //升序
Arrays.sort(numss, Collections.reverseOrder()); //标准库方法
使用PriorityQueue对HashMap按key键升序,降序
public class Main {
public static void main(String[] args) throws IOException {
HashMap<String,Integer> map = new HashMap<>();
map.put("a",1);
map.put("c",3);
map.put("d",4);
map.put("f",6);
map.put("e",5);
map.put("b",2);
//和上面不同的是这里排序规则是比较key的,key是String类型,不能使用-比较,使用.compareTo()比较
PriorityQueue<Map.Entry<String,Integer>> queue = new PriorityQueue<>((e1,e2) -> e1.getKey().compareTo(e2.getKey())); //按键升序
PriorityQueue<Map.Entry<String,Integer>> queue = new PriorityQueue<>((e1,e2) -> e2.getKey().compareTo(e1.getKey())); //按键降序
queue.addAll(map.entrySet());
int size = queue.size();
for(int i=0;i<size;i++){
System.out.println(queue.poll());
}
}
}
使用PriorityQueue对HashMap按value键升序,降序
public class Main {
public static void main(String[] args) throws IOException {
HashMap<String,Integer> map = new HashMap<>();
//模拟数据
map.put("a",1);
map.put("c",3);
map.put("d",4);
map.put("f",6);
map.put("e",5);
map.put("b",2);
//创建优先队列并设置排序规则,
PriorityQueue<Map.Entry<String,Integer>> queue = new PriorityQueue<>((e1,e2) -> e1.getValue() - e2.getValue()); //按value升序
PriorityQueue<Map.Entry<String,Integer>> queue = new PriorityQueue<>((e1,e2) -> e2.getValue() - e1.getValue()); //按value降序
//将map的Entry加入到优先队列中
queue.addAll(map.entrySet());
//获取到优先队列的长度,由于下面使用poll来拿到栈顶元素,使用poll方法后长度会减1,因此循环次数需要固定
int size = queue.size();
//优先队列使用堆来维护的,因此不能够直接遍历优先队列,你会发现直接遍历取出来的值不一定是按顺序
//这里需要使用取出栈顶元素,取出一个元素后,优先队列会自动维护堆
for(int i=0;i<size;i++){
System.out.println(queue.poll());
}
}
}
使用PriorityQueue对HashMap多级排序
//先按value排序,value相同时再按key排序
PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>(
(a,b) -> {
if (a.getValue() == b.getValue()) {
return a.getKey().compareTo(b.getKey());
} else {
return b.getValue() - a.getValue();
}
}
);

浙公网安备 33010602011771号