-
Notifications
You must be signed in to change notification settings - Fork 0
/
19.5 Comparator vs Comparable.java
90 lines (68 loc) · 1.65 KB
/
19.5 Comparator vs Comparable.java
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Comparator;
//class Student implements Comparable<Student>
class Student
{
int age;
String name;
public Student(int age, String name)
{
this.age=age;
this.name=name;
}
public String toString() {
return "Student [age=" + age + ", name=" +name +"]";
}
// public int CompareTo(Student that)
// {
//// return 0;
// if(this.age >that.age)
// return 1;
// else
// return -1;
// }
}
public class Demo {
public static void main(String[] args){
// Comparator<Integer> com=new Comparator<Integer>()
// {
// public int compare(Integer i,Integer j)
// {
// if(i%10 >j%10)
// return 1;
// else
// return -1;
// }
// };
// List<Integer> nums= new ArrayList<>();
// nums.add(43);
// nums.add(31);
// nums.add(72);
// nums.add(29);
// Comparator<Student> com=new Comparator<Student>()
// {
// public int compare(Student i,Student j)
// {
// if(i.age >j.age)
// return 1;
// else
// return -1;
// }
// };
Comparator<Student> com=(i,j) -> i.age > j.age?1:-1;
List<Student> studs= new ArrayList<>();
studs.add(new Student(21,"ali"));
studs.add(new Student(12,"amir"));
studs.add(new Student(18,"erfan"));
studs.add(new Student(20,"omid"));
// Collections.sort(nums);
// System.out.println(nums);
for(Student s:studs)
System.out.println();
Collections.sort(studs);
for(Student s: studs)
System.out.println(s);
}
}