Sort List in Java 7

DZone > Java Zone > Java 8 Comparator: How to Sort a List

Java 8 Comparator: How to Sort a List

Want to sort your Lists? Look no further. Check out the variety of ways you can get your Lists just the way you want them.

by

Mario Pio Gioiosa

CORE ·

May. 20, 19 · Java Zone · Tutorial

Like [67]

Comment

Save

Tweet

516.88K Views

Join the DZone community and get the full member experience.

Join For Free

In this article,were going to see several examples on how to sort a List in Java 8.

Sort a List of Strings Alphabetically

List cities = Arrays.asList[ "Milan", "london", "San Francisco", "Tokyo", "New Delhi" ]; System.out.println[cities]; //[Milan, london, San Francisco, Tokyo, New Delhi] cities.sort[String.CASE_INSENSITIVE_ORDER]; System.out.println[cities]; //[london, Milan, New Delhi, San Francisco, Tokyo] cities.sort[Comparator.naturalOrder[]]; System.out.println[cities]; //[Milan, New Delhi, San Francisco, Tokyo, london]

Weve written London with a lowercase "L" to better highlight differences betweenComparator.naturalOrder[], whichreturns a Comparator that sortsby placing capital letters first, andString.CASE_INSENSITIVE_ORDER, which returns a case-insensitive Comparator.

Basically, in Java 7, we were using Collections.sort[] that was accepting a List and, eventually, a Comparator in Java 8 we havethe newList.sort[], which acceptsa Comparator.

Sort a List of Integers

List numbers = Arrays.asList[6, 2, 1, 4, 9]; System.out.println[numbers]; //[6, 2, 1, 4, 9] numbers.sort[Comparator.naturalOrder[]]; System.out.println[numbers]; //[1, 2, 4, 6, 9]

Sort a List by String Field

Lets suppose we have our Movie class and we want to sort our Listby title.We can use Comparator.comparing[]and pass a function that extracts the field to usefor sorting title, in this example.

List movies = Arrays.asList[ new Movie["Lord of the rings"], new Movie["Back to the future"], new Movie["Carlito's way"], new Movie["Pulp fiction"]]; movies.sort[Comparator.comparing[Movie::getTitle]]; movies.forEach[System.out::println];

The output will be:

Movie{title='Back to the future'} Movie{title='Carlito's way'} Movie{title='Lord of the rings'} Movie{title='Pulp fiction'}

As youve probably noticed, we havent passed a Comparator, but theList is correctly sorted. Thats because title, the extracted field, is a String, and a String implements aComparable interface. If you peek at theComparator.comparing[] implementation, you will see that it callscompareToon the extracted key.

return [Comparator & Serializable] [c1, c2] -> keyExtractor.apply[c1].compareTo[keyExtractor.apply[c2]];

Sort a List by DoubleField

In a similar way, we can use Comparator.comparingDouble[] for comparing double value. In the example, we want to order our List of movies by rating, from the highest to the lowest.

List movies = Arrays.asList[ new Movie["Lord of the rings", 8.8], new Movie["Back to the future", 8.5], new Movie["Carlito's way", 7.9], new Movie["Pulp fiction", 8.9]]; movies.sort[Comparator.comparingDouble[Movie::getRating] .reversed[]]; movies.forEach[System.out::println];

We used thereversed function on the Comparatorin order to invert default natural order; that is, from lowest to highest. Comparator.comparingDouble[] uses Double.compare[] under the hood.

If you need to compare int or long, you can usecomparingInt[] andcomparingLong[] respectively.

Sort a ListWith a Custom Comparator

In the previous examples, we havent specified any Comparator since it wasnt necessary, but lets see an example in which we define our ownComparator. Our Movie class has a newfield starred set using the third constructor parameter. In the example, we want to sort the list so that wehave starred movies at the top of the List.

List movies = Arrays.asList[ new Movie["Lord of the rings", 8.8, true], new Movie["Back to the future", 8.5, false], new Movie["Carlito's way", 7.9, true], new Movie["Pulp fiction", 8.9, false]]; movies.sort[new Comparator[] { @Override public int compare[Movie m1, Movie m2] { if[m1.getStarred[] == m2.getStarred[]]{ return 0; } return m1.getStarred[] ? -1 : 1; } }]; movies.forEach[System.out::println];

The result will be:

Movie{starred=true, title='Lord of the rings', rating=8.8} Movie{starred=true, title='Carlito's way', rating=7.9} Movie{starred=false, title='Back to the future', rating=8.5} Movie{starred=false, title='Pulp fiction', rating=8.9}

We can, of course, use a lambda expression instead of Anonymous class, as follows:

movies.sort[[m1, m2] -> { if[m1.getStarred[] == m2.getStarred[]]{ return 0; } return m1.getStarred[] ? -1 : 1; }];

We can also use Comparator.comparing[] again:

movies.sort[Comparator.comparing[Movie::getStarred, [star1, star2] -> { if[star1 == star2]{ return 0; } return star1 ? -1 : 1; }]];

In the last example, Comparator.comparing[] takes the function to extract the key to usefor sorting as the first parameter, and a Comparator as thesecond parameter. This Comparator uses the extracted keys for comparison; star1 and star2are booleanand represent m1.getStarred[] and m2.getStarred[]respectively.

Sort a ListWith Chain ofComparators

In the last example, we want to have starred movie at the top and then sort by rating.

List movies = Arrays.asList[ new Movie["Lord of the rings", 8.8, true], new Movie["Back to the future", 8.5, false], new Movie["Carlito's way", 7.9, true], new Movie["Pulp fiction", 8.9, false]]; movies.sort[Comparator.comparing[Movie::getStarred] .reversed[] .thenComparing[Comparator.comparing[Movie::getRating] .reversed[]] ]; movies.forEach[System.out::println];

And the output is:

Movie{starred=true, title='Lord of the rings', rating=8.8} Movie{starred=true, title='Carlito's way', rating=7.9} Movie{starred=false, title='Pulp fiction', rating=8.9} Movie{starred=false, title='Back to the future', rating=8.5}

As youve seen, we first sort by starredand then by rating both reversed because we want highest value and true first.

Topics:

java 8, sorting, lists, lambda expression

Published at DZone with permission of Mario Pio Gioiosa, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Kafka vs Chronicle for Microservices
  • Sustaining Agile Transformation Our Experience
  • Multiple Inheritance in Java
  • Proxy Design Pattern in Java

Comments

Java Partner Resources

Video liên quan

Chủ Đề