Java 8: Comparator Example [Snippet]

DZone 's Guide to

Java 8: Comparator Example [Snippet]

Want to learn more about how to use the Comparator class in Java 8? Check out this code snippet on using the Comparator and Person class!

· Java Zone ·
Free Resource

I would like to sort a list of the objects with two fields via the Java 8 Comparator class.

Assume you have Person class as demonstrated in the following code:

public class Person {       
  private String name;    
  private boolean active;

  //getters & setters    
  public String getName() {return name;}
  public void setName(String name) {this.name = name;}
  public boolean isActive() {return active;}
  public void setActive(boolean active) {this.active = active;}

And, you have a list of the Person class. In addition, you should sort this by name and the active field. 

At first, I want to sort the persons that have the active field equal to true, and then, I need to sort their name by alphabet. For implementing this case, you can use the Comparator in Java 8. This is similar to the following code:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ComparatorExample {
  public static void main(String[] args) {
    // -- initiate some data
    List<Person> personList = new ArrayList<>();
    boolean active = true;
    for(int index = 0 ; index <10;index++){
      Person person = new Person();
      active = !active;// even are active and odds are inactive
    // create Comparator in order to sort
    Comparator<Person> sortByActiveAndName = Comparator.comparing(Person::isActive)
    // sort personList
    // display sorted personList
    personList.forEach(user -> System.out.println("name:"+user.getName()+" , " + "active:" + user.isActive()));

As you can see, from line 7 to 15, I initiated data for working on it. The important lines are 17 to 19, so you should define the appropriate comparator in order to sort the two fields. Therefore, when you use the Comparator class, it is static and there are some useful methods. The comparing method makes it possible to sort the field. I used the reversed method because if you do not, the list of data will put persons, which have active fields that are false, at the beginning of the list. By using the  reverse(), you can change it in the opposite way.

So far, so good. Now, the next field will be name, because it is the string type and will sort alphabetically. After running this example you will see the following output:

name:name0 , active:true
name:name2 , active:true
name:name4 , active:true
name:name6 , active:true
name:name8 , active:true
name:name1 , active:false
name:name3 , active:false
name:name5 , active:false
name:name7 , active:false
name:name9 , active:false

Happy Sorting!

java ,java8 ,tutorial ,comparator ,class ,sorting

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}