-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollectionInterface6.java
More file actions
82 lines (66 loc) · 1.9 KB
/
CollectionInterface6.java
File metadata and controls
82 lines (66 loc) · 1.9 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//Comparator vs Comparable
import java.util.ArrayList;
import java.util.Collections;
// import java.util.Comparator;
import java.util.List;
//Without comparator and using 'Comparable'!
//We dont use comparator, we implement Comparable and func compareTo() (Mimic comparator here!)
class Student implements Comparable<Student>{
int age;
String name;
public Student(int age, String name){
this.age = age;
this.name = name;
}
@Override
public String toString(){
return "Student [ age = "+age+" ,name = "+name+" ]";
}
public int compareTo(Student that){
if(this.age > that.age){
return 1;
}
else{
return -1;
}
}
}
public class CollectionInterface6{
public static void main(String args[]){
// Comparator<Student> com3 = new Comparator<Student>(){
// @Override
// public int compare(Student s1,Student s2){
// if(s1.age > s2.age){
// return 1;
// }
// else{
// return -1;
// }
// }
// };
// or
//this is func interface! we can use lambda function
// Comparator<Student> com3 = (Student s1,Student s2) -> {
// return s1.age>s2.age? 1:-1;
// };
//or
//single line of code for comparator!
// Comparator<Student> com3 = (s1, s2) -> return s1.age>s2.age? 1:-1;
List<Student> students = new ArrayList<>();
students.add(new Student(22,"Killer"));
students.add(new Student(14,"JD"));
students.add(new Student(35,"Rolex"));
students.add(new Student(66,"Dhilli"));
students.add(new Student(10,"perry"));
//comparator is an interface
//using comparator, we can implement custom sorting techniques!
// Collections.sort(students,com3);
//comparable
//we mimic the functionality of comparator with 'comparable'!
//since we implement Comparable in Student class, we dont need to pass comparator! (We actually dont need it).
Collections.sort(students); // without comparator!
for(Student s: students){
System.out.println(s);
}
}
}