Java lambda sorted comparator

How to use Java Lambda expression for sorting a List using comparator

The following examples illustrate how to use Lambda expressions — the main feature coming with Java SE 8 — to improve the boilerplate code of comparator written for sorting list collections.

Suppose that we have the following model class:

class Book < private String title; private float price; Book(String title, float price) < this.title = title; this.price = price; >// getters and setters public String toString() < return this.title + "-" + this.price; >>
Book book1 = new Book("Head First Java", 38.9f); Book book2 = new Book("Thinking in Java", 30.0f); Book book3 = new Book("Effective Java", 50.0f); Book book4 = new Book("Code Complete", 42.5f); List listBooks = Arrays.asList(book1, book2, book3, book4);

Now, we want to sort this list by the book’s attributes such as title and price (ascending and descending). Let’s see how Lambda expressions can make the comparator code more concise compared with classic code (before Java 8).

1. Sorting a Java list collection in the classic way

As a way mentioned in the article Sorting List Collections Examples, we can write a comparator to sort the list. For example, the following code creates a comparator which compares two books by their titles:

Comparator titleComparator = new Comparator() < public int compare(Book book1, Book book2) < return book1.getTitle().compareTo(book2.getTitle()); >>;
Collections.sort(listBooks, titleComparator);
System.out.println("\nAfter sorting by title:"); System.out.println(listBooks);
After sorting by title: [Code Complete-42.5, Effective Java-50.0, Head First Java-38.9, Thinking in Java-30.0]

2. Sorting a Java list collection using Lambda expression

Since Java 8 with Lambda expressions support, we can write a comparator in a more concise way as follows:

Comparator descPriceComp = (Book b1, Book b2) -> (int) (b2.getPrice() - b1.getPrice());

This comparator compares two books by their prices which cause the list to be sorted in descending order of prices, using the Lambda expression:

(Book b1, Book b2) -> (int) (b2.getPrice() - b1.getPrice());

Here, a Lambda expression can be used because the Comparator interface declares only one method — compareTo() — so the compiler can infer the method’s signature. Then pass this comparator into the Collections.sort() method as normal:

Collections.sort(listBooks, descPriceComp);
System.out.println("\nAfter sorting by descending price:"); System.out.println(listBooks);
After sorting by price descending: [Effective Java-50.0, Code Complete-42.5, Head First Java-38.9, Thinking in Java-30.0]

In the Lambda expression, we can even safely remove the types of the parameters because the compiler can infer them from the declared type Comparator . Here’s a more concise version of the Lambda expression:

(b1, b2) -> (int) (b1.getPrice() - b2.getPrice())
Collections.sort(listBooks, (b1, b2) -> (int) (b1.getPrice() - b2.getPrice()));
System.out.println("\nAfter sorting by ascending price:"); System.out.println(listBooks);
After sorting by price ascending: [Thinking in Java-30.0, Head First Java-38.9, Code Complete-42.5, Effective Java-50.0]

3. List Sorting Example Program using Lambda Expression

package net.codejava.lambda; import java.util.*; /** * This program demonstrates how to use Lambda expressions to improve code of * comparator used to sort list collections. * * @author www.codejava.net */ public class LambdaComparatorExample < public static void main(String[] args) < Book book1 = new Book("Head First Java", 38.9f); Book book2 = new Book("Thinking in Java", 30.0f); Book book3 = new Book("Effective Java", 50.0f); Book book4 = new Book("Code Complete", 42.5f); ListlistBooks = Arrays.asList(book1, book2, book3, book4); System.out.println("Before sorting:"); System.out.println(listBooks); Comparator titleComparator = new Comparator() < public int compare(Book book1, Book book2) < return book1.getTitle().compareTo(book2.getTitle()); >>; Collections.sort(listBooks, titleComparator); System.out.println("\nAfter sorting by title:"); System.out.println(listBooks); Comparator descPriceComp = (Book b1, Book b2) -> (int) (b2.getPrice() - b1.getPrice()); Collections.sort(listBooks, descPriceComp); System.out.println("\nAfter sorting by descending price:"); System.out.println(listBooks); Collections.sort(listBooks, (b1, b2) -> (int) (b1.getPrice() - b2.getPrice())); System.out.println("\nAfter sorting by ascending price:"); System.out.println(listBooks); > > class Book < private String title; private float price; Book(String title, float price) < this.title = title; this.price = price; >String getTitle() < return this.title; >void setTitle(String title) < this.title = title; >float getPrice() < return this.price; >void setPrice(float price) < this.price = price; >public String toString() < return this.title + "-" + this.price; >>
Before sorting: [Head First Java-38.9, Thinking in Java-30.0, Effective Java-50.0, Code Complete-42.5] After sorting by title: [Code Complete-42.5, Effective Java-50.0, Head First Java-38.9, Thinking in Java-30.0] After sorting by price descending: [Effective Java-50.0, Code Complete-42.5, Head First Java-38.9, Thinking in Java-30.0] After sorting by price ascending: [Thinking in Java-30.0, Head First Java-38.9, Code Complete-42.5, Effective Java-50.0]

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

Comments

just in the lambda description the methode CompareTo() is within the Comparable Interface and not in Comparator that contains compare(), and thank you for this helpful content;

CodeJava.net shares Java tutorials, code examples and sample projects for programmers at all levels.
CodeJava.net is created and managed by Nam Ha Minh — a passionate programmer.

Copyright © 2012 — 2023 CodeJava.net, all rights reserved.

Источник

Java Comparator with Lambda

The Comparator interface is used to sort a collection of objects that can be compared. The object comparison can be made using Comparable interface as well, but it restricts us by comparing objects in a specific single way only. If we want to sort this collection, based on multiple criteria/fields, then we have to use Comparator only.

Comparator comparator = Comparator.comparing(User::firstName); Collections.sort(list, comparator);

To demo the concept, we are using the record User with four attributes. We will use it to understand various use cases.

public record User(Long id, String firstName, String lastName, Integer age)

2. Creating Comparator without Lambda

If we are not using lambda expressions, we can create a Comparator instance using an anonymous inner class. In the following example, we are creating a Comparator instance that compares the two instances of User class by their firstName property.

Comparator byNameComparator = new Comparator() < @Override public int compare(User u1, User u2) < return u1.firstName().compareTo(u2.firstName()); >>;

Lambda expressions are code blocks that take arguments and return a value. They are similar to anonymous methods. We can use the lambda expressions to create Comparator instances in a much short form. For example, we can rewrite the previous byNameComparator as follows:

Comparator firstNameComparator = (User u1, User u2) -> u1.firstName().compareTo(u2.firstName());

Lambda expressions allow omitting the type definitions. The compiler infers the types by the variable type.

Comparator firstNameComparator = (u1, u2) -> u1.firstName().compareTo(u2.firstName());

We can further simplify the expression by using the method reference as follows:

Comparator firstNameComparator = Comparator.comparing(User::firstName);

What if we want to sort the list by first name but in reversed order. It’s really very easy; use Comparator.reversed() method.

Comparator firstNameComparator = Comparator.comparing(User::firstName); Comparator reverseComparator = firstNameComparator.reverse();

Here we are sorting the list of employees first by their first name, then by their last name. Just as we apply to sort SQL statements. Now we don’t always need to use sorting on multiple fields in SQL select statements, we can sort them in java as well.

Comparator fullNameComparator = Comparator.comparing(User::firstName).thenComparing(User::lastName);

We can sort the collection of objects in parallel using multiple threads as well. It will be very fast if the collection is big enough to have thousands of objects. For a small collection of objects, normal sorting is good enough and recommended.

Comparator firstNameComparator = Comparator.comparing(User::firstName); Arrays.parallelSort(usersArray, firstNameComparator);

That’s all for using lambda with Comparator to sort objects. Please share with all of us if you know more techniques around this concept.

Источник

Java 8 Lambda Comparator example for Sorting List of Custom Objects

We have already seen how to sort an Arraylist of custom Objects without using lambda expression. In this tutorial we will see how to sort a list of custom objects using lambda expression in Java.

Before we see the complete example, lets see what is the difference between using lambda vs without using lambda:

Without using Lambda expression: Before Java 8 we sort like this:

If you are not familiar with the Comparator, refer this guide: Java Comparator with example.

Here we are sorting a list of objects of Student class by name.

Comparator sortingByName = new Comparator() < @Override public int compare(Student s1, Student s2) < return s1.getName().compareTo(s2.getName()); >>;

Using Lambda expression: The Java 8 equivalent code using Lambda expression would look like this:

Comparator sortingByName = (Student s1, Student s2)->s1.getName().compareTo(s2.getName());

Note: In Java 8, the List interface supports the sort() method so you need not to use the Comparator.sort(), instead you can use the List.sort() method. The above code can be further re-written as:
Here studentlist is the instance of the list containing Student objects (see the complete example below).

studentlist.sort((Student s1, Student s2)->s1.getName().compareTo(s2.getName()));

Java 8 – Sorting with Lambda Expression

import java.util.ArrayList; import java.util.List; class Student < String name; int age; int id; public String getName() < return name; >public int getAge() < return age; >public int getId() < return id; >Student(String n, int a, int i) < name = n; age = a; >@Override public String toString() < return ("Student[ "+"Name:"+this.getName()+ " Age: "+ this.getAge() + " Id: "+ this.getId()+"]"); >> public class Example < public static void main(String[] args) < Liststudentlist = new ArrayList(); studentlist.add(new Student("Jon", 22, 1001)); studentlist.add(new Student("Steve", 19, 1003)); studentlist.add(new Student("Kevin", 23, 1005)); studentlist.add(new Student("Ron", 20, 1010)); studentlist.add(new Student("Lucy", 18, 1111)); System.out.println("Before Sorting the student data:"); //java 8 forEach for printing the list studentlist.forEach((s)->System.out.println(s)); System.out.println("After Sorting the student data by Age:"); //Lambda expression for sorting by age studentlist.sort((Student s1, Student s2)->s1.getAge()-s2.getAge()); //java 8 forEach for printing the list studentlist.forEach((s)->System.out.println(s)); System.out.println("After Sorting the student data by Name:"); //Lambda expression for sorting the list by student name studentlist.sort((Student s1, Student s2)->s1.getName().compareTo(s2.getName())); studentlist.forEach((s)->System.out.println(s)); System.out.println("After Sorting the student data by Id:"); //Lambda expression for sorting the list by student id studentlist.sort((Student s1, Student s2)->s1.getId()-s2.getId()); studentlist.forEach((s)->System.out.println(s)); > >
Before Sorting the student data: Student[ Name:Jon Age: 22 Id: 1001] Student[ Name:Steve Age: 19 Id: 1003] Student[ Name:Kevin Age: 23 Id: 1005] Student[ Name:Ron Age: 20 Id: 1010] Student[ Name:Lucy Age: 18 Id: 1111] After Sorting the student data by Age: Student[ Name:Lucy Age: 18 Id: 1111] Student[ Name:Steve Age: 19 Id: 1003] Student[ Name:Ron Age: 20 Id: 1010] Student[ Name:Jon Age: 22 Id: 1001] Student[ Name:Kevin Age: 23 Id: 1005] After Sorting the student data by Name: Student[ Name:Jon Age: 22 Id: 1001] Student[ Name:Kevin Age: 23 Id: 1005] Student[ Name:Lucy Age: 18 Id: 1111] Student[ Name:Ron Age: 20 Id: 1010] Student[ Name:Steve Age: 19 Id: 1003] After Sorting the student data by Id: Student[ Name:Jon Age: 22 Id: 1001] Student[ Name:Steve Age: 19 Id: 1003] Student[ Name:Kevin Age: 23 Id: 1005] Student[ Name:Ron Age: 20 Id: 1010] Student[ Name:Lucy Age: 18 Id: 1111]

Java 8 – Sorting in reverse order

To sort the list in the reverse(descending) order, just change the order of the arguments like this:

Sorting the list of objects of Student class by Name in reverse order:

studentlist.sort((Student s1, Student s2)->s2.getName().compareTo(s1.getName()));

Similarly, the list can be sorted in reverse order by student age and id like this:

//Lambda expression for sorting the list by student age in reverse order studentlist.sort((Student s1, Student s2)->s2.getAge()-s1.getAge()); //Lambda expression for sorting the list by student id in reverse order studentlist.sort((Student s1, Student s2)->s2.getId()-s1.getId());

Related Tutorials:

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

Читайте также:  Python binary files read write
Оцените статью