Java Collection: Comparator Interface - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Java Collection: Comparator Interface

Share This
The Comparator interface in java.util is a useful utility for ordering the user-defined class objects. It contains two methods (i) compare(Object obj1,Object obj2) (compares the first object with the second object) and equals(Object element).

The following example shows, how this interface is used.

Source code of Item.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.t4b.test;
public class Item {
String name;
int id;
double price;
public Item(String name, int id, double price) {
super();
this.name = name;
this.id = id;
this.price = price;
}
@Override
public String toString() {
return "Item [name=" + name + ", id=" + id + ", price=" + price + "]";
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Source code of IdComparator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.t4b.test;
import java.util.Comparator;
public class IdComparator implements Comparator<Item> {
@Override
public int compare(Item o1, Item o2) {
if (o1.id == o2.id)
return 0;
else if (o1.id > o2.id)
return 1;
else
return -1;
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Source code of IdComparator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.t4b.test;
import java.util.Comparator;
public class IdComparator implements Comparator<Item> {
@Override
public int compare(Item o1, Item o2) {
return o1.name.compareTo(o2.name);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Source code of TestMain.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
package com.t4b.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class TestMain {
public static void main(String[] args) {
ArrayList<Item> items = new ArrayList<Item>();
items.add(new Item("Apple", 1, 150.0));
items.add(new Item("Bag", 3, 1050.0));
items.add(new Item("Grape", 2, 250.0));
Collections.sort(items, new NameComparator());
Iterator<Item> itr = items.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
Collections.sort(items, new IdComparator());
itr = items.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.