![]() It returns a comparator that compares Comparable objects in natural order. It is used to compare the current object with the specified object. It accepts a function that extracts a long sort key from a type T, and returns a Comparator that compares by that sort key. Static Comparator comparingLong(ToLongFunction keyExtractor) It accepts a function that extracts an int sort key from a type T, and returns a Comparator that compares by that sort key. Static Comparator comparingInt(ToIntFunction keyExtractor) It accepts a function that extracts a double sort key from a type T, and returns a Comparator that compares by that sort key. Static Comparator comparingDouble(ToDoubleFunction keyExtractor) It accepts a function that extracts a sort key from a type T, and returns a Comparator that compares by that sort key using the specified Comparator. Static Comparator comparing(Function keyExtractor, Comparator ke圜omparator) It accepts a function that extracts a Comparable sort key from a type T, and returns a Comparator that compares by that sort key. It compares the first object with second object.Ĭomparator comparing(Function keyExtractor) Methods of Java 8 Comparator Interface Method Now, we can use the Comparator interface as the assignment target for a lambda expression or method reference. Java 8 Comparator interface is a functional interface that contains only one abstract method. This class contains three fields rollno, name and age and a parameterized constructor. In this example, we have created 4 java classes: Let's see the example of sorting the elements of List on the basis of age and name. ![]() ![]() Java Comparator Example (Non-generic Old Style) Public void sort(List list, Comparator c): is used to sort the elements of List by the given Comparator. Method of Collections class for sorting List elements Collections class provides methods for sorting the elements of List type elements also. However, we cannot sort the elements of List. If collection elements are of Set or Map, we can use TreeSet or TreeMap. Public boolean equals(Object obj) It is used to compare the current object with the specified object.Ĭollections class provides static methods for sorting the elements of a collection. Public int compare(Object obj1, Object obj2) It compares the first object with the second object. Methods of Java Comparator Interface Method It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data member, for example, rollno, name, age or anything else. This interface is found in java.util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element). Java Comparator interface is used to order the objects of a user-defined class.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |