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
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 + "]";
}
}
Source code of IdComparator.java
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;
}
}
Source code of IdComparator.java
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);
}
}
Source code of TestMain.java
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());
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.