Comparable and comparator in java

  1. java
  2. Comparable and Comparator in Java
  3. Comparable and Comparator Example in Java
  4. Comparable and Comparator in Java – Difference Between Them
  5. Comparable vs Comparator in Java
  6. The Important Differences Between Comparable and Comparator
  7. Java Sort Arrays Examples (with Comparable and Comparator)
  8. Interview Question — Comparable vs Comparator


Download: Comparable and comparator in java
Size: 16.8 MB

java

Assume you have some objects which have several fields they can be compared by: public class Person So in this example, when you ask if: a.compareTo(b) > 0 you might be asking if a's last name comes before b's, or if a is older than b, etc... What is the cleanest way to enable multiple comparison between these kinds of objects without adding unnecessary clutter or overhead? • java.lang.Comparable interface allows comparison by one field only • Adding numerous compare methods (i.e. compareByFirstName(), compareByAge(), etc...) is cluttered in my opinion. So what is the best way to go about this? With Java 8: Comparator.comparing((Person p)->p.firstName) .thenComparing(p->p.lastName) .thenComparingInt(p->p.age); If you have accessor methods: Comparator.comparing(Person::getFirstName) .thenComparing(Person::getLastName) .thenComparingInt(Person::getAge); If a class implements Comparable then such comparator may be used in compareTo method: @Override public int compareTo(Person o) You should implement Comparable . Assuming all fields will not be null (for simplicity sake), that age is an int, and compare ranking is first, last, age, the compareTo method is quite simple: public int compareTo(Person other) @ars-longa-vita-brevis, If you are using Comparable then sorting logic must be in the same class whose objects are being sorted so this is called natural ordering of objects. With the use of Comparator you can write custom sorting logic outside the Person class. If you want ...

Comparable and Comparator in Java

Overview We all are familiar with sorting data of primitive data types like int, String, char, etc. We can pass the array to the Arrays.sort() method directly, and Java takes care of sorting those values because Java is aware of how to sort numbers, characters, or strings. But what about the custom objects we create like Student, Employee and so on. Java is unaware of how to sort these custom objects, and we need to provide the logic to sort these custom objects explicitly. Java provides two interfaces, Comparable and Comparator, that can be used to sort custom objects and objects based on multiple data members. Introduction to Comparable and Comparator in Java Comparable and Comparator, it is clear from the name that these are used to compare things. In Java, it may be a value or an object. But how does it differ from each other? This article will explain the working of Comparable and Comparator in Java with a real-time example. Consider building a • GET /superheroes Returns all the superheroes ordered by id in ascending order. • GET /superheroes?sort=name Returns all the superheroes ordered by name in ascending order. • GET /superheroes?sort=age Returns all the superheroes ordered by age in ascending order. Before going further, let's create the SuperHero class with three attributes id, name, and age. We will be using this class in the further parts of this article. What is Comparable in Java? Comparable is an interface in Java that enables comparing an object with other...

Comparable and Comparator Example in Java

In Java when it comes to sort any collections, comparable and comparator comes into picture. Comparable and Comparator are two interfaces provided by Java Core API.Here we will take a look into why Comparable and Comparator are used for sorting though there are inbuilt methods provide by Java API to sort primitive types array or Wrapper classes array or list.What are the use cases to choose Comparable for sorting and in which scenario Comparator should be preferred.Now, let's see how to use Comparator and Comparable in Java with example. Comparable Interface The Comparable interface is used by the Collections.sort() method and the java.util.Arrays.sort() method to sort the Lists and arrays of objects respectively.At first, let's quickly look into a simple example and will discuss more about it. Here the Employee class implements Comparable and overrides it's compareTo() method to sort the employee object based on it's name. public class Employee implements Comparable Now if you have a collection of employee objects then it can be used as below for sorting: //populate the employeeList by dummy records or get from DB List employeeList = new ArrayList(); //Sort the emplyeeList by it's name in ascending order Collections.sort(employeeList); Now what if we want to sort Employee collection based on age.Since we sorted our ArrayList by implementing compareTo() method, we seem to stuck. We can only implement compareTo() once in a class, so how to sort the list again by some other ...

Comparable and Comparator in Java – Difference Between Them

Key Difference between Comparable and Comparator in Java • Comparable in Java is an object to compare itself with another object, whereas Comparator is an object for comparing different objects of different classes. • Comparable provides the compareTo() method to sort elements in Java, whereas Comparator provides compare() method to sort elements in Java. • A comparable interface is present in java.lang package, whereas the Comparator interface is present in java.util package. • Comparable provides a single sorting sequence, while Comparator provides multiple sorting sequences. • Comparable affects the original class, whereas comparator doesn’t affect the original class. Difference between Comparator vs Comparable in Java What is Comparable in Java? Comparable in Java is an object to compare itself with another object. It helps to sort the list of custom objects. The java.lang.Comparable interface should be implemented by a class in order to compare its instances. Array of objects implementing a comparable interface is sorted automatically by Arrays.sort and Collections.sort methods. What is Comparator in Java? Comparator in Java is an object for comparing different objects of different classes. Comparator interface in Java is also used to arrange the objects of user-defined classes. It includes two important comparator interface methods known as compare (Object obj1, Object obj2) and equals (Object element). Differences between Comparable and Comparator in Java Here is th...

Comparable vs Comparator in Java

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface to compare its instances. Consider a Movie class that has members like, rating, name, year. Suppose we wish to sort a list of Movies based on year of release. We can implement the Comparable interface with the Movie class, and we override the method compareTo() of Comparable interface. Movies after sorting : Star Wars 8.7 1977 Empire Strikes Back 8.8 1980 Return of the Jedi 8.4 1983 Force Awakens 8.3 2015 Now, suppose we want to sort movies by their rating and names as well. When we make a collection element comparable(by having it implement Comparable), we get only one chance to implement the compareTo() method. The solution is using Using Comparator Unlike Comparable, Comparator is external to the element type we are comparing. It’s a separate class. We create multiple separate classes (that implement Comparator) to compare by different members. Collections class has a second sort() method and it takes Comparator. The sort() method invokes the compare() to sort objects. To compare movies by Rating, we need to do 3 things: • Create a class that implements Comparator (and thus the compare() method that does the work previously done by compareTo()). • Make an instance of the Comparator class. • Call the overloaded sort() method, giving it both the list and the instance of the class that implements Comparator. Output: Sorted by rating 8....

The Important Differences Between Comparable and Comparator

Sorting is a common operation on lists/collections, such as to arrange the content into a particular order. In a list, sorting is done according to the natural ordering of the content, but this may not always be the case. Sorting in Lists The content of lists in Java are sorted according to natural order. This means that, if the content are numbers, it is sorted as ascending or lowest to highest order when sorted. Similarly, characters are sorted according to their alphabetical order. But, this may not always be the case we need. There must be some way to override the natural ordering principle on the content of the list. Java provides two interfaces to help with the sort according to our custom requirement. These two are called Comparable and Comparator. They are declared as a public interface by the Java API so that we can use them to fit our requirements. The Comparable and Comparator Interfaces The Comparable interface imposes a total ordering on the implemented class. This total ordering is referred to as the natural ordering. The comparison for ordering is asserted by the compareTo method of this interface, called the natural ordering method. Collections and lists are automatically sorted by the set of overloaded static variation of the Collection.sort and Arrays.sort methods. For example, the overloaded sort methods defined by the Collection are follows: • static > void sort(List list): This method sorts the specified list into ascending order. • static void sort(L...

Java Sort Arrays Examples (with Comparable and Comparator)

This tutorial helps you how to use the You know, the java.util.Arrays class provides various methods for sorting elements of an array, as simple as: Arrays.sort(array)This tutorial shows various examples of sorting an array using such methods, especially using the Comparable and Comparator interfaces. But first, let’s look at the implementation details of sorting algorithms in JDK. The sorting algorithms in JDK For primitive arrays, a tuned version of O(n log(n)) performance but the Dual-Pivot Quicksort is typically faster. For Object arrays, a modified version of O(n log n) performance in average and worst cases; runs faster if the array is partially sorted; and it won’t re-order equal elements. 1. Sorting an array of primitivesThe following example shows how easy it is to sort an array of primitives (e.g. integer numbers): int[] numbers = ; java.util.Arrays.sort(numbers); Putting two System.out.println() statements to print the array’s elements before and after sorting: int[] numbers = ; System.out.println("Before sorting: " + Arrays.toString(numbers)); Arrays.sort(numbers, 0, 5); System.out.println("Sorted a half: " + Arrays.toString(numbers));Output: Before sorting: [4, 9, 1, 3, 2, 8, 7, 0, 6, 5] Sorted a half: [1, 2, 3, 4, 9, 8, 7, 0, 6, 5]And the following example sorts just 3 employees based on their ages, using a comparator: Arrays.sort(newEmployees, 0, 3, new EmployeeAgeComparator()); 6. ConclusionSo far we have gone through examples of sorting arrays using variou...

Interview Question — Comparable vs Comparator

What is the difference between Comparable and Comparator? It’s a very popular entry/mid-level Java interview question, isn’t it? Candidates often start comparing interfaces based on their method signatures and how we implement and use them. But, we generally miss the intent or use-cases of these interfaces. Before we understand the differences, we need to understand what is the natural ordering? Let me ask you a question — if I don’t provide any extra information and give you a list of numbers or string values like names then how would you sort them? You’d say numbers in ascending order and names in alphabetical order. But why? You’d say it feels natural, isn’t it.? Well, what’s what natural order is all about. We don’t need any extra information, we simply know how to sort them. Now, consider I ask you to sort a list of students. You’d probably say — how? By roll number, by name, by date of birth, or by their marks? Here, we need extra information because Student doesn’t have a natural order. Using Comparable Using Comparator Now, we come back to the question. Everything is secondary but the main thing to remember about these interfaces is that if we’re defining the natural order of an entity/class then we use Comparable. Natural order == Comparable What would be the natural order of a Student? Finalizing the natural order of an entity depends on the requirement and use-case. In case of Student class, if we decide it to be by roll number then we would implement Comparable...