Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Java8 uses Lambda expressions to compare

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article shows you how Java8 uses Lambda expressions to compare. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Prior to Java 8, sorting collections required the creation of an anonymous inner class for the comparator Comparator used in sorting:

New Comparator () {@ Override public int compare (Human H2, Human h3) {return h2.getName () .compareTo (h3.getName ());}}

This is only used to sort the list of Human entities:

@ Testpublic void givenPreLambda_whenSortingEntitiesByName_thenCorrectlySorted () {List humans = Lists.newArrayList (new Human ("Sarah", 10), new Human ("Jack", 12)); Collections.sort (humans, new Comparator () {@ Override public int compare (Human H2, Human h3) {return h2.getName () .compareTo (h3.getName ());}}) Assert.assertThat (humans.get (0), equalTo (new Human ("Jack", 12));} supports basic sorting of Lambda

With the introduction of Lambdas, we can now bypass anonymous inner classes and achieve the same result through simple function semantics:

(final Human H2, final Human h3)-> h2.getName (). CompareTo (h3.getName ())

Similarly, we can now test the behavior as before:

@ Testpublic void whenSortingEntitiesByName_thenCorrectlySorted () {List humans = Lists.newArrayList (new Human ("Sarah", 10), new Human ("Jack", 12)); humans.sort ((Human H2, Human h3)-> h2.getName (). CompareTo (h3.getName ()); assertThat (humans.get (0), equalTo (new Human ("Jack", 12));}

Notice that we also use the newly sorted API that we added to java. Java.util.List lists the Collections.sort using Java8 instead of the old collection.

Basic sorting without type definition

We can further simplify expressions by not specifying type definitions; the compiler can infer the following on its own:

(H2, h3)-> h2.getName (). CompareTo (h3.getName ())

Again, the tests are still very similar:

@ Testpublic void givenLambdaShortForm_whenSortingEntitiesByName_thenCorrectlySorted () {List humans = Lists.newArrayList (new Human ("Sarah", 10), new Human ("Jack", 12)); humans.sort ((H2, h3)-> h2.getName (). CompareTo (h3.getName ()); assertThat (humans.get (0), equalTo (new Human ("Jack", 12));} sort using reference static method

Next, we will use Lambda expressions and references to static methods to perform sorting.

First, we will define the CompareBynametEnable method with exactly the same signature as the compare method in the Comparator object:

Public static int compareByNameThenAge (Human lhs, Human rhs) {if (lhs.name.equals (rhs.name)) {return Integer.compare (lhs.age, rhs.age);} else {return lhs.name.compareTo (rhs.name);}}

Then we will call humans.sort to use the sorting method of this reference:

Humans.sort (Human::compareByNameThenAge)

The end result is to sort the collection's work using a static method as a comparator:

@ Testpublic void givenMethodDefinition_whenSortingEntitiesByNameThenAge_thenCorrectlySorted () {List humans = Lists.newArrayList (new Human ("Sarah", 10), new Human ("Jack", 12)); humans.sort (Human::compareByNameThenAge); Assert.assertThat (humans.get (0), equalTo (new Human ("Jack", 12));} Sort Extracted Comparators

By using instance method references and comparators, we can even avoid defining the comparison logic itself. Comparison method, which is based on this function to extract and create comparable.

We will use getName () to build the Lambda expression and sort the list by name:

@ Testpublic void givenInstanceMethod_whenSortingEntitiesByName_thenCorrectlySorted () {List humans = Lists.newArrayList (new Human ("Sarah", 10), new Human ("Jack", 12)); Collections.sort (humans, Comparator.comparing (Human::getName)); assertThat (humans.get (0), equalTo (new Human ("Jack", 12));} reverse sort

JDK 8 also introduces an auxiliary method to reverse the comparator. We can quickly use this to reverse our ordering:

@ Testpublic void whenSortingEntitiesByNameReversed_thenCorrectlySorted () {List humans = Lists.newArrayList (new Human ("Sarah", 10), new Human ("Jack", 12)); Comparator comparator = (H2, h3)-> h2.getName () .compareTo (h3.getName ()); humans.sort (comparator.reversed ()); Assert.assertThat (humans.get (0), equalTo (new Human ("Sarah", 10) } sort using multiple criteria

Comparing lambda expressions doesn't have to be so simple. We can also write more complex expressions, such as sorting entities by name and then by age:

@ Testpublic void whenSortingEntitiesByNameThenAge_thenCorrectlySorted () {List humans = Lists.newArrayList (new Human ("Sarah", 12), new Human ("Sarah", 10), new Human ("Zack", 12)); humans.sort ((lhs, rhs)-> {if (lhs.getName (). Equals (rhs.getName () {return Integer.compare (lhs.getAge (), rhs.getAge ()) } else {return lhs.getName () .compareTo (rhs.getName ());}}); Assert.assertThat (humans.get (0), equalTo (new Human ("Sarah", 10));} sort with multiple conditions-combine

The same comparison logic, sorted first by name and then by age, can also be implemented through the new composition support.

Starting with JDK 8, we can now link multiple comparators together to build more complex comparison logic:

Testpublic void givenComposition_whenSortingEntitiesByNameThenAge_thenCorrectlySorted () {List humans = Lists.newArrayList (new Human ("Sarah", 12), new Human ("Sarah", 10), new Human ("Zack", 12)); humans.sort (Comparator.comparing (Human::getName) .thencomparing (Human::getAge)); Assert.assertThat (humans.get (0), equalTo (new Human ("Sarah", 10) } sort the list using Stream.sorted ()

We can also sort collections using Stream sorted () API of Java 8.

We can sort the stream using natural sorting and the sort provided by the comparator. To do this, we have two overloaded variants of sorted () API:

Sorted ()-sorts elements using natural sort convection; the element class must implement a comparable interface.

Sorted (Comparator

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: 0

*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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report