Skip to content

Commit de566bb

Browse files
committed
feat(ComparatorDemo2): add demo of custom comparators for integers and strings
What - Added StringLengthComparator: - Implements Comparator<String>. - Compares two strings by their length. - Returns negative if first is shorter, positive if longer, 0 if equal. - Added MyComparator: - Implements Comparator<Integer>. - Compares integers by subtraction (ascending order). - Added ComparatorDemo2 main class: - Example 1: Creates a list of integers [2,3,9,7,1], sorts using MyComparator, prints result. - Example 2: Creates a list of strings ["banana","apple","date"], sorts using StringLengthComparator, prints result. Why - Demonstrates how to implement and use custom comparators for flexible sorting. - Highlights the power of Comparator to define multiple external orderings for the same data type. - Educational example showing comparator usage beyond natural ordering. How - Defined two comparator classes implementing Comparator interface. - In main(): - list.sort(new MyComparator()) sorts integers ascending. - words.sort(new StringLengthComparator()) sorts strings by length ascending. - Printed results to verify. Logic - Inputs: - Integers: [2,3,9,7,1]. - Strings: ["banana","apple","date"]. - Outputs: - Integers sorted ascending: [1,2,3,7,9]. - Strings sorted by length ascending: ["date","apple","banana"]. - Flow: 1. list.sort() calls compare() from MyComparator → orders numbers. 2. words.sort() calls compare() from StringLengthComparator → orders by string length. - Edge cases: - MyComparator’s subtraction could overflow for large values; safer to use Integer.compare(o1,o2). - StringLengthComparator’s subtraction is safe, but Integer.compare(o1.length(), o2.length()) is clearer. - Complexity / performance: O(n log n). - Concurrency / thread-safety: Local lists only; not thread-safe in multi-thread contexts. - Error handling: None required. Real-life applications - Sorting by string length (useful for formatting, UI, word games). - Sorting integers or custom objects with specific rules (ranking, thresholds). - Comparators allow different ordering without modifying the class. Notes - Comparator.comparingInt(String::length) is a cleaner functional alternative to StringLengthComparator. - Integer::compare avoids overflow issues. - This demo illustrates the verbose, explicit class-based comparator approach for clarity. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 55041b0 commit de566bb

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.List;
4+
import java.util.*;
5+
6+
// Comparator to compare Strings based on their length
7+
class StringLengthComparator implements Comparator<String> {
8+
9+
public int compare(String o1, String o2) {
10+
// return 0;
11+
// If you want to treat all strings as equal
12+
13+
// return Integer.compare(o1.length(), o2.length());
14+
// Alternative way to compare by length
15+
16+
return o1.length() - o2.length(); // Compare based on string length
17+
/*
18+
Example Logic:
19+
o1 o2
20+
"Ok" "Bye"
21+
→ "Ok".length() = 2
22+
→ "Bye".length() = 3
23+
→ 2 - 3 = -1 (so "Ok" comes before "Bye")
24+
*/
25+
}
26+
}
27+
28+
// Comparator to compare Integers in ascending order
29+
class MyComparator implements Comparator<Integer> {
30+
@Override
31+
public int compare(Integer o1, Integer o2) {
32+
return o1 - o2; // Positive if o1 > o2, Negative if o1 < o2
33+
/*
34+
Example:
35+
o1 = 5, o2 = 3 → 5 - 3 = 2 (5 comes after 3)
36+
o1 = 3, o2 = 5 → 3 - 5 = -2 (3 comes before 5)
37+
*/
38+
}
39+
}
40+
41+
public class ComparatorDemo2 {
42+
public static void main(String[] args) {
43+
// Comparator in Java is very important when sorting based on custom logic.
44+
45+
// Example 1: Sorting integers using MyComparator
46+
List<Integer> list = new ArrayList<>();
47+
list.add(2);
48+
list.add(3);
49+
list.add(9);
50+
list.add(7);
51+
list.add(1);
52+
53+
list.sort(new MyComparator()); // Use MyComparator to sort integers
54+
System.out.println("Sorted integers: " + list);
55+
56+
// Example 2: Sorting strings based on their length using StringLengthComparator
57+
List<String> words = Arrays.asList("banana", "apple", "date");
58+
59+
words.sort(new StringLengthComparator()); // Use StringLengthComparator to sort by length
60+
System.out.println("Sorted strings by length: " + words);
61+
}
62+
}

0 commit comments

Comments
 (0)