Hi Guys,
When shall we use Comparator interface?
Comparator example.
Good day :)
What is Comparator interface?
1. Comparator interface provide comparison function, which imposes a total ordering on some collection of objects.
2. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order.
3. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.
3. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.
When shall we use Comparator interface?
If you have more than one sorting criterias then you have to go for Comparator.
Comparator example.
User.java
class User{ private String name; private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
NameComparator.java
class NameComparator implements Comparator{ @Override public int compare(User firstUser, User secondUser) { return firstUser.getName().compareTo(secondUser.getName()); } }
AgeComparator.java
class AgeComparator implements Comparator{ @Override public int compare(User firstUser, User secondUser) { if(firstUser.getAge()==secondUser.getAge()) return 0; else if(firstUser.getAge()>secondUser.getAge()) return 1; else return -1; } }
Main.java
class Main { public static void main(String[] args) { User fistUserObj = new User(); fistUserObj.setName("Ram"); fistUserObj.setAge(11); User secondUserObj = new User(); secondUserObj.setName("Shyam"); secondUserObj.setAge(12); User thirdUserObj = new User(); thirdUserObj.setName("Ghanshyam"); thirdUserObj.setAge(13); List<user> userList = new ArrayList<user>(); userList.add(fistUserObj); userList.add(secondUserObj); userList.add(thirdUserObj); System.out.println("Name Comparator"); Collections.sort(userList, new NameComparator()); Iterator<user> nameIterator = userList.iterator(); while(nameIterator.hasNext()){ User user = nameIterator.next(); System.out.println(user.getName()+":"+user.getAge()); } System.out.println(); System.out.println("Age Comparator"); Collections.sort(userList, new AgeComparator()); Iterator<user> ageIterator = userList.iterator(); while(ageIterator.hasNext()){ User user = ageIterator.next(); System.out.println(user.getName()+":"+user.getAge()); } } }
Output
Name Comparator Ghanshyam:13 Ram:11 Shyam:12 Age Comparator Ram:11 Shyam:12 Ghanshyam:13
Good day :)
0 Comments