int[] 数组排序
升序排序:
Arrays.sort(num);
降序排序:
num= IntStream.of(num) // 变为 IntStream
.boxed() // 变为 Stream<Integer>
.sorted(Comparator.reverseOrder()) // 按自然序相反排序
.mapToInt(Integer::intValue) // 变为 IntStream
.toArray();
Integer[]、String[] 数组排序
升序排序:
Arrays.sort(num);
降序排序:
Arrays.sort(num, Collections.reverseOrder());
List排序
升序排序:
Collections.sort(num);
降序排序:
Collections.sort(num, Collections.reverseOrder());
Set排序
set不支持直接排序,可转换成List然后进行排序,需要频繁操作有序可以参考TreeSet👇
TreeSet
Set->List
Set<Integer> numbers = new HashSet<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
numbers.add(9);
// 将Set转换为List
List<Integer> sortedList = new ArrayList<>(numbers);
// 升序排序
Collections.sort(sortedList);
// 降序排序
Collections.sort(sortedList, Collections.reverseOrder());
Map排序
map也不支持直接排序
可以使用TreeMap来进行**键(Key)**的排序。
TreeMap<String, Integer> treeMap = new TreeMap<>(); //按key升序排序
TreeMap<String, Integer> treeMap = new TreeMap<>(Collections.reverseOrder());//按key降序排序
遍历
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
想实现当前数组通过别的数组进行排序(力扣2948题解题技巧)
只能使用Integer不能使用int
Integer[] ids = new Integer[n];
for(int i=0;i<n;i++)
ids[i] = i;
Arrays.sort(ids,(i,j)->nums[i]-nums[j]); //把id的数按照nums的大小进行排序。
👆这个方法可以记录nums按值的大小排序时候的每个数的原始位置是多少(ids数组就是记录的位置)。
//Arrays.copyOfRange左闭右开区间
Integer[] subIds = Arrays.copyOfRange(ids, begin, i);
按对象中的某个值排序(对象数组)
//int[][] rides
Arrays.sort(rides, (a, b) -> a[1] - b[1]); //按int[]数组中的第二个中排序(顺序)
优先队列排序
PriorityQueue<long[]> pq = new PriorityQueue<long[]>((a, b) -> Long.compare(a[0], b[0]));
PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
👆这段代码是Java中创建一个PriorityQueue对象的示例,该对象用于存储long[](长整型数组)类型的元素,并根据数组中第一个元素的自然顺序(从小到大)进行排序。
下面是代码的分解:
PriorityQueue<long[]> pq: 声明了一个名为pq的PriorityQueue对象,该对象用于存储long[](长整型数组)类型的元素。
new PriorityQueue<long[]>(…): 使用PriorityQueue的构造函数创建一个新的PriorityQueue对象。
(a, b) -> Long.compare(a[0], b[0]): 这是一个Lambda表达式,它定义了一个比较器(Comparator),用于确定PriorityQueue中元素的顺序。
a 和 b 是PriorityQueue中两个要比较的元素,它们都是long[]类型的数组。
Long.compare(a[0], b[0]) 比较a数组的第一个元素和b数组的第一个元素。如果a[0]小于b[0],则返回负数;如果a[0]等于b[0],则返回零;如果a[0]大于b[0],则返回正数。
PriorityQueue<Integer> queue = new PriorityQueue<Integer>(new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2){
return o1.compareTo(o2);
}
});
字符串数组排序方法
Arrays.sort(nums_s,(a,b)-> {
String ab = a+b;
String ba = b+a;
return ba.compareTo(ab);
}
对象排序方法
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()>o2.getAge()? -1:(o1.getAge()==o2.getAge()? 0:1);
}
});
质数(素数)的简单求法
public static boolean isPrime(int n) {
int i = 2;
for (; i <= Math.sqrt(n); i++) {
if(n % i == 0) {
return false;
}
}
if(i > Math.sqrt(n)) {
return true;
}
}