-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJava_Comparator_2.java
More file actions
84 lines (70 loc) · 1.87 KB
/
Java_Comparator_2.java
File metadata and controls
84 lines (70 loc) · 1.87 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
83
84
package technicals;
import java.util.*;
import java.io.*;
//Here we are sorting each time with different or a single field.
class Student
{
int age;
String name,stream;
public Student(int age,String name,String stream)
{
this.name=name;
this.age=age;
this.stream=stream;
}
@Override
public String toString()
{
// Returning attributes of Student in the below format
return this.name + " of " + this.stream + " is of "+ this.age+" age.";
}
}
//implementing Comparator<Student> to sort in terms of age
class SortByAge implements Comparator<Student>
{
@Override
public int compare(Student a , Student b)
{
return a.age-b.age;
}
}
//implementing Comparator<Student> to sort in terms of Name
class SortByName implements Comparator<Student>
{
@Override
public int compare(Student a, Student b)
{
return a.name.compareTo(b.name);
}
}
public class J_Comparator_2 {
public static void main(String[] args) throws IOException
{
BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Limit");
ArrayList<Student> list = new ArrayList<>();//Creating an empty ArrayList of Student type
int n = Integer.parseInt(inp.readLine());
System.out.println("Enter the student details: \nIn the format of age, name, stream");
for(int i =1;i<=n;i++)
{
list.add(new Student(Integer.parseInt(inp.readLine()),inp.readLine(),inp.readLine()));
}
System.out.println("\nIn Unsorted Format:");
for(Student i :list)
{
System.out.println(i);
}
System.out.println("\nSorted in respective to age:");
Collections.sort(list, new SortByAge());
for(Student i :list)
{
System.out.println(i);
}
System.out.println("\nSorted in respective to name:");
Collections.sort(list, new SortByName());
for(Student i :list)
{
System.out.println(i);
}
}
}