How to use Comparator with Lambda in java 8?

Here is a some example to explain how to use Comparator with Lambda in java 8?

1-  with Sort a simple List

package com.nourit.java8;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorWithLambda {

  public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
    System.out.println("-------------- List bevor Sort --------------------");
    System.out.println("The List:     " + list);
    
    System.out.println("-------------- Simple Comparator Sort without Lambda--------------------");
    Collections.sort(list, new Comparator<Integer>() {
      @Override
      public int compare(Integer a, Integer b) {
        return b.compareTo(a);
      }
    });
    System.out.println("The List:     " + list);
    
    System.out.println("-------------- Java 8 Comparaotr Sort with Lambda--------------------");
    Collections.sort(list, (a, b) -> b.compareTo(a));
    System.out.println("The List:     " + list);
    System.out.println("-------------- ------------------ --------------------");
  }
}

Output:

-------------- List bevor Sort --------------------
The List:     [1, 2, 3, 4, 5, 6, 7, 8, 9]
-------------- Simple Comparator Sort without Lambda--------------------
The List:     [9, 8, 7, 6, 5, 4, 3, 2, 1]
-------------- Java 8 Comparaotr Sort with Lambda--------------------
The List:     [9, 8, 7, 6, 5, 4, 3, 2, 1]
-------------- ------------------ --------------------

2-  Sort – Object with Lambda and Comparator

we need a class Person as Object:

class Person {
  private int id;
  private String name;
  private String firstname;
  private String country;

  public Person(int id, String firstname, String name, String country) {
    this.id = id;
    this.name = name;
    this.firstname = firstname;
    this.country = country;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getFirstname() {
    return firstname;
  }

  public void setFirstname(String firstname) {
    this.firstname = firstname;
  }

  public String getCountry() {
    return country;
  }

  public void setCountry(String country) {
    this.country = country;
  }
}
  • First Example Sort with Lambda by id
package com.nourit.java8;

import java.util.Arrays;
import java.util.List;

public class ComparatorWithLambda1 {

  public static List<Person> getPersonList() {
    return Arrays.asList(
        new Person(3, "Dennis", "Müller", "Kanada"), 
        new Person(2, "Sonja", "Fischer", "Germany"),
        new Person(4, "Maria", "Kuhn", "Austria"), 
        new Person(1, "Ahmed", "charkawi", "Morocco"));
  }

  public static void main(String[] args) {
    List<Person> personList = getPersonList();
    System.out.println("-------------- Read a List With normal Bevor Sort--------------------");
    for (Person person : personList) {
      System.out.println(person.getId() + " " + person.getName() + " " + person.getFirstname() + " " + person.getCountry());
    }

    //Sort without Lambda by id
//		Collections.sort(personList, new Comparator<Person>() {
//			@Override
//			public int compare(Person p1, Person p2) {
//				return p1.getId() - p2.getId();
//			}
//		});
    
    //Sort with Lambda by id
    personList.sort((Person p1, Person p2)-> p1.getId() - p2.getId());
    
    System.out.println("-------------- Read a List With ForEach After Sort--------------------");
    personList.forEach((Person person) -> {
      System.out.println(person.getId() + " " + person.getName() + " " + person.getFirstname() + " " + person.getCountry());
    });
    System.out.println("--------------------------------------------");

  }
}

Output:

-------------- Read a List With normal Bevor Sort--------------------
3 Müller Dennis Kanada
2 Fischer Sonja Germany
4 Kuhn Maria Austria
1 charkawi Ahmed Morocco
-------------- Read a List With ForEach After Sort--------------------
1 charkawi Ahmed Morocco
2 Fischer Sonja Germany
3 Müller Dennis Kanada
4 Kuhn Maria Austria
--------------------------------------------
  • Second Example Sort with Lambda by Name
package com.nourit.java8;

import java.util.Arrays;
import java.util.List;

public class ComparatorWithLambda2 {

  public static List<Person> getPersonList() {
    return Arrays.asList(
        new Person(3, "Dennis", "Müller", "Kanada"), 
        new Person(2, "Sonja", "Fischer", "Germany"),
        new Person(4, "Maria", "Kuhn", "Austria"), 
        new Person(1, "Ahmed", "Charkawi", "Morocco"));
  }

  public static void main(String[] args) {
    List<Person> personList = getPersonList();
    System.out.println("-------------- Read a List With normal Bevor Sort--------------------");
    for (Person person : personList) {
      System.out.println(person.getId() + " " + person.getName() + " " + person.getFirstname() + " " + person.getCountry());
    }

    //Sort without Lambda by name
//		Collections.sort(personList, new Comparator<Person>() {
//			@Override
//			public int compare(Person p1, Person p2) {
//				return p1.getName().compareTo(p2.getName());
//			}
//		});
    
    //Sort with Lambda by name
    //personList.sort((p1, p2)-> p1.getName().compareTo(p2.getName())); // Or
    personList.sort((Person p1, Person p2)-> p1.getName().compareTo(p2.getName()));
    
    System.out.println("-------------- Read a List With ForEach After Sort--------------------");
    personList.forEach((Person person) -> {
      System.out.println(person.getId() + " " + person.getName() + " " + person.getFirstname() + " " + person.getCountry());
    });
    System.out.println("--------------------------------------------");

  }

}

Output:

-------------- Read a List With normal Bevor Sort--------------------
3 Müller Dennis Kanada
2 Fischer Sonja Germany
4 Kuhn Maria Austria
1 Charkawi Ahmed Morocco
-------------- Read a List With ForEach After Sort--------------------
1 Charkawi Ahmed Morocco
2 Fischer Sonja Germany
4 Kuhn Maria Austria
3 Müller Dennis Kanada
--------------------------------------------
  • Tirth Example Sort with Lambda by ID and Name using funktional Interfaces

Lambda Sort with Multiple Conditions

package com.nourit.java8;

import java.util.Arrays;
import java.util.List;

public class ComparatorWithLambda3 {

  public static List<Person> getPersonList() {
    return Arrays.asList(
        new Person(3, "Dennis", "Müller", "Kanada"), 
        new Person(2, "Sonja", "Fischer", "Germany"),
        new Person(4, "Maria", "Kuhn", "Austria"), 
        new Person(1, "Ahmed", "Charkawi", "Morocco"));
  }

  public static void main(String[] args) {
    List<Person> personList = getPersonList();
    System.out.println("-------------- Read a List With normal Bevor Sort--------------------");
    for (Person person : personList) {
      System.out.println(person.getId() + " " + person.getName() + " " + person.getFirstname() + " " + person.getCountry());
    }

    //Sort without Lambda by Country
//		Collections.sort(personList, new Comparator<Person>() {
//			@Override
//			public int compare(Person p1, Person p2) {
//				return p1.getCountry().compareTo(p2.getCountry());
//			}
//		});
    
    System.out.println("-------------- Read a List With ForEach After Sort--------------------");
    //Sort with Lambda by Country
    //personList.sort((p1, p2)-> p1.getCountry().compareTo(p2.getCountry())); // Or
    //personList.sort((Person p1, Person p2)-> p1.getCountry().compareTo(p2.getCountry()));
    
    //with funktional Interfaces
    Compare compare = (Person p1, Person p2)-> {
       if (p1.getName().equals(p2.getName())) {
              return p1.getId() - p2.getId();
          } else {
              return p1.getName().compareTo(p2.getName());
          }
    };
    personList.sort((Person p1, Person p2)-> compare.compareByIDAndName(p1, p2));
    
    personList.forEach((Person person) -> {
      System.out.println(person.getId() + " " + person.getName() + " " + person.getFirstname() + " " + person.getCountry());
    });
    System.out.println("--------------------------------------------");
  }
  
  interface Compare{
    int compareByIDAndName(Person p1, Person p2);
  }
}

Output:

-------------- Read a List With normal Bevor Sort--------------------
3 Müller Dennis Kanada
2 Fischer Sonja Germany
4 Kuhn Maria Austria
1 Charkawi Ahmed Morocco
-------------- Read a List With ForEach After Sort--------------------
1 Charkawi Ahmed Morocco
2 Fischer Sonja Germany
4 Kuhn Maria Austria
3 Müller Dennis Kanada
--------------------------------------------
  • Fourth Example Sort with Lambda by Name using reversing the comparator
package com.nourit.java8;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class ComparatorWithLambda4 {

  public static List<Person> getPersonList() {
    return Arrays.asList(
        new Person(3, "Dennis", "Müller", "Kanada"), 
        new Person(2, "Sonja", "Fischer", "Germany"),
        new Person(4, "Maria", "Kuhn", "Austria"), 
        new Person(1, "Ahmed", "Charkawi", "Morocco"));
  }

  public static void main(String[] args) {
    List<Person> personList = getPersonList();
    System.out.println("-------------- Read a List With normal Bevor Sort--------------------");
    for (Person person : personList) {
      System.out.println(
          person.getId() + " " + person.getName() + " " + person.getFirstname() + " " + person.getCountry());
    }
    
    // with reversing the comparator
    Comparator<Person> comparator = (p1, p2) -> (p1.getId() - p2.getId());
    
    System.out.println("-------------- Read a List With ForEach After Sort Without Reversed--------------------");
    personList.sort(comparator);
    personList.forEach((Person person) -> {
      System.out.println(
          person.getId() + " " + person.getName() + " " + person.getFirstname() + " " + person.getCountry());
    });
    
    System.out.println("-------------- Read a List With ForEach After Sort With Reversed--------------------");
    personList.sort(comparator.reversed());
    
    personList.forEach((Person person) -> {
      System.out.println(
          person.getId() + " " + person.getName() + " " + person.getFirstname() + " " + person.getCountry());
    });
    System.out.println("--------------------------------------------");
  }
}

Output:

-------------- Read a List With normal Bevor Sort--------------------
3 Müller Dennis Kanada
2 Fischer Sonja Germany
4 Kuhn Maria Austria
1 Charkawi Ahmed Morocco
-------------- Read a List With ForEach After Sort Without Reversed--------------------
1 Charkawi Ahmed Morocco
2 Fischer Sonja Germany
3 Müller Dennis Kanada
4 Kuhn Maria Austria
-------------- Read a List With ForEach After Sort With Reversed--------------------
4 Kuhn Maria Austria
3 Müller Dennis Kanada
2 Fischer Sonja Germany
1 Charkawi Ahmed Morocco
--------------------------------------------

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*