Sort List in Java 7
Show
DZone > Java Zone > Java 8 Comparator: How to Sort a List Java 8 Comparator: How to Sort a ListWant 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 · TutorialLike (67) Comment Save Tweet 516.88K Views Join the DZone community and get the full member experience. Join For FreeIn this article,were going to see several examples on how to sort a List in Java 8. Sort a List of Strings AlphabeticallyListWeve 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 IntegersListSort a List by String FieldLets 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. ListThe 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 (ComparatorSort a List by DoubleFieldIn 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. ListWe 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 ComparatorIn 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. ListThe 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 ofComparatorsIn the last example, we want to have starred movie at the top and then sort by rating. ListAnd 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
Comments Java Partner Resources |