Java 常用小技巧(Loading...)
1、HashMap 排序:
下面这条代码在数据量过大时排序出错,可以在LeetCode的题目中进行这条语句的测试,连接—> 1333. 餐厅过滤器
Collections.sort(li, ((o1, o2) -> o1.getValue() == o2.getValue() ? o2.getKey() - o1.getKey() : o2.getValue() - o1.getValue()));
下面的排序代码在目前的测试题目中还都是正确的(本人自己写的,并已经测试正确)
List<Map.Entry<Integer,Integer>> li = new ArrayList<Map.Entry<Integer,Integer>>(); //将 Map 转成 List 再进行排序 li.addAll(map.entrySet()); //将你的map存进去,你命名的也可能是myMap 那么就是li.addAll(myMap.entrySet()); Collections.sort(li,new Comparator<Map.Entry<Integer,Integer>>(){ public int compare(Map.Entry<Integer,Integer> e1,Map.Entry<Integer,Integer> e2){ //这个排序样例 是先将Value值降序,再将Key值降序
int re = e2.getValue().compareTo(e1.getValue()); //排序比较的时候 e2 在前,说明是按从高到低排序 if(re!=0){return re;} //如果 re == 0 说明两个值相等 else{return e2.getKey().compareTo(e1.getKey());} } }); List<Integer> list = new ArrayList<>(); for(Iterator <Map.Entry<Integer,Integer>>it = li.iterator(); it.hasNext();){ //将Map的排序结果依次输出,并将Key值存放在list数组中 list.add(it.next().getKey()); }
2、List 转成 int[] (前提是List里面存放的数据是整型):
list.stream().mapToInt(Integer::intValue).toArray();
3、数组转字符串:
例如:此时有数组 int[] s = new int[]{1,6,22,13,25};
经过下边这条语句,会将int型数组中的数字转成对应的小写字母,之后再将小写字母拼接成String字符串。
String ans = Arrays.stream(str).boxed().map(i -> (char)('a' + i - 1) + "").collect(Collectors.joining());
运行后的ans:"afvmy"
4、PriorityQueue 优先队列的使用 :
优点:方便存储多组数据进行队列存储
缺点:不能存储不同数据类型的数据
下面这段代码表示的是将数组存放到优先队列中,o2[1] - o1[1] 代表该优先队列按照 数组中第二个元素 从大到小排列
Queue<int[]> queue = new PriorityQueue<>((o1, o2) -> o2[1] - o1[1]);
//获取优先队列 头部的 数组中的第一个元素 queue.peek()[0]; //获取优先队列 头部的 数组中的第二个元素 queue.peek()[1]; //获取删除 优先队列的头部数组 queue.poll(); //将新数组插入 优先队列中 queue.offer(new int[]{a, b});
5、java数组求和 (适合非等差数组):
Arrays.stream().sum();
↑
放入需求和的数组
int[] nums = new int[]{1, 4, 5, 8}; int total = Arrays.stream(nums).sum();
6、持续更新中... :

浙公网安备 33010602011771号