Skip to content

Commit 48548e3

Browse files
author
JavaProgramTo.com
committed
Anonymous Comparator
1 parent 35f9387 commit 48548e3

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.javaprogramto.java8.comparator.anonymous;
2+
3+
import java.util.Arrays;
4+
import java.util.Comparator;
5+
6+
public class AnonymousComparatorArrayExample {
7+
8+
public static void main(String[] args) {
9+
10+
String[] stringArray = new String[5];
11+
12+
stringArray[0] = "abc";
13+
stringArray[1] = "mno";
14+
stringArray[2] = "def";
15+
stringArray[3] = "xyz";
16+
stringArray[4] = "ghi";
17+
18+
System.out.println("Array before sorting - " + stringArray);
19+
20+
Arrays.sort(stringArray, new Comparator() {
21+
22+
@Override
23+
public int compare(Object o1, Object o2) {
24+
25+
String str1 = (String) o1;
26+
String str2 = (String) o2;
27+
return str1.compareTo(str2);
28+
}
29+
30+
});
31+
32+
System.out.println("Array after sorting with anonymous comparator - " + stringArray);
33+
34+
}
35+
36+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.javaprogramto.java8.comparator.anonymous;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.Comparator;
6+
import java.util.List;
7+
8+
public class AnonymousComparatorListExample {
9+
10+
public static void main(String[] args) {
11+
12+
List<String> strings = new ArrayList<>();
13+
14+
strings.add("abc");
15+
strings.add("mno");
16+
strings.add("def");
17+
strings.add("xyz");
18+
strings.add("ghi");
19+
20+
System.out.println("List before sorting - " + strings);
21+
22+
Collections.sort(strings, new Comparator() {
23+
24+
@Override
25+
public int compare(Object o1, Object o2) {
26+
27+
String str1 = (String) o1;
28+
String str2 = (String) o2;
29+
return str1.compareTo(str2);
30+
}
31+
32+
});
33+
34+
System.out.println("List after sorting with anonymous comparator - " + strings);
35+
36+
Job job1 = new Job() {
37+
38+
@Override
39+
public void post() {
40+
System.out.println("Posting job 1 now");
41+
42+
}
43+
};
44+
45+
}
46+
47+
}
48+
49+
interface Job {
50+
void post();
51+
}

0 commit comments

Comments
 (0)