-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCompare.java
More file actions
59 lines (48 loc) · 1.45 KB
/
Compare.java
File metadata and controls
59 lines (48 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package lambda;
import java.util.Arrays;
import java.util.Comparator;
/**
* Created by Edwin Xu on 5/3/2020 3:05 PM
*/
public class Compare {
public void f(){
//排序整数
Integer arr[] = {1,2,3,34,2,-23,30,-34,90};//不能使用基本类型,是泛型
Arrays.sort(arr);//默认从小到大
for (int i :arr)System.out.print(i);
System.out.println();
//使用自定义比较器
class MyCompare implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
}
Arrays.sort(arr,new MyCompare());
for (int i :arr) System.out.print(i);
System.out.println();
//使用lambda表达式
Arrays.sort(arr,(a,b)->a-b);
for (int i :arr)System.out.print(i);
System.out.println();
Arrays.sort(arr,
(a,b)->{
int a_ = a;
int b_ = b;
return b_-a_;
});
for (int i :arr)System.out.print(i);
System.out.println();
Arrays.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
for (int i :arr)System.out.print(i);
System.out.println();
}
public static void main(String[] args) {
new Compare().f();
}
}