The method reference is given as Class::method. When we sort objects, the comparing and thenComparing methods are given a reference to the object's type - the method is called in order and the values returned by the method are compared. The thenComparing method can be used many times by chaining methods, which allows virtually unlimited values to be used for comparison. The comparing method is passed the value to be compared first, and the thenComparing method is the next value to be compared. The Comparator class provides two essential methods for sorting: comparing and thenComparing. We'll use the same Member class as the type parameter. The Comparable interface takes as its type parameter the class that is the subject of the comparison. The club members should go to eat in order of height, so the Member class should implement the Comparable interface. Let's take a look at this with the help of a Member class that represents a child or youth who belongs to a club. The sorting resulting from the compareTo method is called natural ordering. If, on the other hand, the "this" object comes after the object received as a parameter, the method should return a positive number. If the "this" object comes before the object received as a parameter in terms of sorting order, the method should return a negative number. The compareTo method required by the Comparable interface receives as its parameter the object to which the "this" object is compared. If a class implements the Comparable interface, objects created from that class can be sorted using Java's sorting algorithms. The Comparable interface defines the compareTo method used to compare objects. In the previous section, we looked at interfaces in more general terms - let's now familiarize ourselves with one of Java's ready-made interfaces. You know how to sort list elements using multiple criteria (e.g., you know how to sort a person based on name and age).You know how to use Java's tools for sorting lists and stream elements.You're aware of Java's Comparable class and now how to implement it in your own classes.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |