DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Java
  4. Java 8: Comparator Example [Snippet]

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!

Behzad Khosrojerdi user avatar by
Behzad Khosrojerdi
·
Sep. 05, 18 · Code Snippet
Like (4)
Save
Tweet
Share
12.02K Views

Join the DZone community and get the full member experience.

Join For Free

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();
      person.setName("name"+index);
      person.setActive(active);
      active = !active;// even are active and odds are inactive
      personList.add(person);
    }
    // create Comparator in order to sort
    Comparator<Person> sortByActiveAndName = Comparator.comparing(Person::isActive)
      .reversed()
      .thenComparing(Person::getName);
    // sort personList
    personList.sort(sortByActiveAndName);
    // 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:

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 (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • A Gentle Introduction to Kubernetes
  • Accelerating Enterprise Software Delivery Through Automated Release Processes in Scaled Agile Framework (SAFe)
  • Fixing Bottlenecks in Your Microservices App Flows
  • Running Databases on Kubernetes

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: