-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjava_Comparator_comparing.java
72 lines (55 loc) · 1.88 KB
/
java_Comparator_comparing.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
/*
This Java code demonstrates sorting a collection of Book objects using different criteria (book ID and book name).
It showcases the use of comparators with Java's Collections.sort method
and highlights the importance of getter method
*/
import java.util.*;
class Book {
int Bookid;
String bookname;
public Book(int bookid, String bookname) {
Bookid = bookid;
this.bookname = bookname;
}
public int getBookid() {
return Bookid;
}
public String getBookname() {
return bookname;
}
public void setBookid(int bookid) {
Bookid = bookid;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
// Override
public String toString() {
return "{Bookid=" + Bookid + ", bookname=" + bookname + "}";
}
}
class ComparatorDemo {
public static void main(String[] args) {
Book b1 = new Book(55, "Java");
Book b2 = new Book(14, "DS");
Book b3 = new Book(49, "FEE");
Book b4 = new Book(71, "DBMS");
// System.out.println(b1);
// System.out.println(b2);
// System.out.println(b3);
// System.out.println(b4);
ArrayList<Book> al1 = new ArrayList<Book>();
al1.add(b1);
al1.add(b2);
al1.add(b3);
al1.add(b4);
System.out.println("List of Books is: " + al1);
// Sorting elements as per ID
Collections.sort(al1, Comparator.comparing(Book::getBookid));
System.out.println(al1); // will get books as per ascending book id
Collections.sort(al1, Comparator.comparing(Book::getBookname));
System.out.println(al1); // will get books as per ascending book Name as per ABCD format
Collections.sort(al1, Comparator.comparing(Book::getBookid).reversed());
System.out.println(al1); // will get books as per descending book id
}
}