In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces Java how to use Lambda expression to achieve super sorting function, the article is very detailed, has a certain reference value, interested friends must read it!
First, we define a base class, based on which we will demonstrate how to sort in memory.
@ Data@NoArgsConstructor@AllArgsConstructorpublic class Student {private String name; private int age; @ Override public boolean equals (Object o) {if (this = = o) {return true;} if (o = = null | | getClass ()! = o.getClass ()) {return false;} Student student = (Student) o Return age = = student.age & & Objects.equals (name, student.name);} @ Override public int hashCode () {return Objects.hash (name, age);}} sort based on Comparator
Before Java8, we used to sort by implementing the Comparator interface, such as:
New Comparator () {@ Override public int compare (Student H2, Student h3) {return h2.getName () .compareTo (h3.getName ());}}
What is shown here is the definition of an anonymous inner class. If it is a general comparison logic, you can define an implementation class directly. It is also relatively easy to use. The following is the application:
@ Testvoid baseSortedOrigin () {final List students = Lists.newArrayList (new Student ("Tom", 10), new Student ("Jerry", 12)); Collections.sort (students, new Comparator () {@ Override public int compare (Student H2, Student h3) {return h2.getName () .compareTo (h3.getName ());}}) Assertions.assertEquals (students.get (0), new Student ("Jerry", 12);}
Here, Junit5 is used to implement unit testing, which is very suitable for verifying logic.
Because the defined Comparator is sorted using the name field, in Java, the sort of String type is determined by the ASCII code order of a single character, J comes before T, so Jerry comes first.
Replace Comparator anonymous inner classes with Lambda expressions
Anyone who has used Java8's Lamdba should know that anonymous inner classes can be reduced to Lambda expressions that are:
Collections.sort (students, (Student H2, Student h3)-> h2.getName (). CompareTo (h3.getName ())
In Java8, the sort method is added to the List class, so Collections.sort can be directly replaced with:
Students.sort ((Student H2, Student h3)-> h2.getName () .compareTo (h3.getName ()
Based on the type inference of Lambda in Java8, we can abbreviate the specified Student type:
Students.sort ((H2, h3)-> h2.getName (). CompareTo (h3.getName ()
So far, our entire sorting logic can be simplified as follows:
@ Testvoid baseSortedLambdaWithInferring () {final List students = Lists.newArrayList (new Student ("Tom", 10), new Student ("Jerry", 12)); students.sort ((H2, h3)-> h2.getName (). CompareTo (h3.getName ()); Assertions.assertEquals (students.get (0), new Student ("Jerry", 12));} extract public Lambda expressions through static methods
We can define a static method in Student:
Public static int compareByNameThenAge (Student S1, Student S2) {if (s1.name.equals (s2.name)) {return Integer.compare (s1.age, s2.age);} else {return s1.name.compareTo (s2.name);}}
This method needs to return a parameter of type int, which we can use in Lambda in Java8:
@ Testvoid sortedUsingStaticMethod () {final List students = Lists.newArrayList (new Student ("Tom", 10), new Student ("Jerry", 12)); students.sort (Student::compareByNameThenAge); Assertions.assertEquals (students.get (0), new Student ("Jerry", 12));} comparing method with Comparator
In Java8, the comparator class adds a comparing method that allows you to use the passed Function parameter as a comparison element, such as:
@ Testvoid sortedUsingComparator () {final List students = Lists.newArrayList (new Student ("Tom", 10), new Student ("Jerry", 12)); students.sort (Comparator.comparing (Student::getName)); Assertions.assertEquals (students.get (0), new Student ("Jerry", 12));} Multi-conditional sorting
We showed multi-conditional sorting in the static methods section, and we can also implement multi-conditional logic in Comparator anonymous inner classes:
@ Testvoid sortedMultiCondition () {final List students = Lists.newArrayList (new Student ("Tom", 10), new Student ("Jerry", 12), new Student ("Jerry", 13)); students.sort ((S1, S2)-> {if (s1.getName (). Equals (s2.getName () {return Integer.compare (s1.getAge (), s2.getAge ()) } else {return s1.getName () .compareTo (s2.getName ());}}); Assertions.assertEquals (students.get (0), new Student ("Jerry", 12));}
From a logical point of view, multi-condition sorting is to first judge the first-level conditions, if equal, and then judge the second-level conditions, and so on. In Java8, you can use comparing and a series of thenComparing to represent multi-level conditional judgment, and the above logic can be simplified as follows:
@ Testvoid sortedMultiConditionUsingComparator () {final List students = Lists.newArrayList (new Student ("Tom", 10), new Student ("Jerry", 12), new Student ("Jerry", 13)); students.sort (Comparator.comparing (Student::getName) .thencomparing (Student::getAge)); Assertions.assertEquals (students.get (0), new Student ("Jerry", 12));}
There can be multiple thenComparing methods here, which are used to express multi-level condition judgment, which is also the convenience of functional programming.
Sort in Stream
In Java8, not only Lambda expression is introduced, but also a new streaming API:Stream API is introduced, in which sorted method is used to sort elements in streaming computation, and Comparator can be passed to implement sorting logic:
@ Testvoid streamSorted () {final List students = Lists.newArrayList (new Student ("Tom", 10), new Student ("Jerry", 12)); final Comparator comparator = (H2, h3)-> h2.getName () .compareTo (h3.getName ()); final List sortedStudents = students.stream () .sorted (comparator) .requests (Collectors.toList ()) Assertions.assertEquals (sortedStudents.get (0), new Student ("Jerry", 12);}
Similarly, we can simplify writing through Lambda:
@ Testvoid streamSortedUsingComparator () {final List students = Lists.newArrayList (new Student ("Tom", 10), new Student ("Jerry", 12)); final Comparator comparator = Comparator.comparing (Student::getName); final List sortedStudents = students.stream () .sorted (comparator) .requests (Collectors.toList ()); Assertions.assertEquals (sortedStudents.get (0), new Student ("Jerry", 12)) } reverse order and reverse sort judgment
Sorting is to judge the order according to the values returned by the compareTo method. If you want to sort them in reverse order, you can simply retrieve the returned values:
@ Testvoid sortedReverseUsingComparator2 () {final List students = Lists.newArrayList (new Student ("Tom", 10), new Student ("Jerry", 12)); final Comparator comparator = (H2, h3)-> h3.getName () .compareTo (h2.getName ()); students.sort (comparator); Assertions.assertEquals (students.get (0), new Student ("Tom", 10));}
As you can see, when we are in positive order, we are h2.getName (). CompareTo (h3.getName ()). Here we turn it upside down, using h3.getName (). CompareTo (h2.getName ()), which achieves the effect of inversion. A private class within java.util.Collections.ReverseComparator is defined in Java's Collections, and element inversion is implemented in this way.
Reverse order with the help of reversed method of Comparator
In Java8, the reversed method is added to realize the reverse order, which is also very easy to use:
@ Testvoid sortedReverseUsingComparator () {final List students = Lists.newArrayList (new Student ("Tom", 10), new Student ("Jerry", 12)); final Comparator comparator = (H2, h3)-> h2.getName () .compareTo (h3.getName ()); students.sort (comparator.reversed ()); Assertions.assertEquals (students.get (0), new Student ("Tom", 10));} define sort reversal in Comparator.comparing
The comparing method also has an overloaded method, java.util.Comparator#comparing (java.util.function.Function
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 250
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.