Wednesday, April 24, 2019

Chain Comparator In Java

Q- How to sort objects with multiple attributes using comparator ?

In java we can do the sorting same like in SQL. We can do sorting on object with multiple attributes.
There are several ways in order to sort a list collection by multiple attributes (keys) of its elements type.

Using A CompareToBuilder : CompareToBuilder.toComparison() 

Step-1: Add apache common lang3 dependency
pom.xml
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.7</version>
</dependency>

text

Code Here


Using Java 8 : Using Comparator.thenComparing()

Person.java

package com.shubh.java8.example;

public class Person {

    int id;
    String name;
    String gender;
    String gamePrefrence;

    public Person(int id, String name, String gender, String gamePrefrence) {
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.gamePrefrence = gamePrefrence;
    }

    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 getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getGamePrefrence() {
        return gamePrefrence;
    }

    public void setGamePrefrence(String gamePrefrence) {
        this.gamePrefrence = gamePrefrence;
    }


    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", gamePrefrence='" + gamePrefrence + "\n"+ '\'' +
                '}';
    }
}


MainClass.java
package com.shubh.java8.example;

import java.util.*;

public class MainClass {

    public static void main(String[] args) {
  
  List<Person> plist = new ArrayList<>();
        pList.add(new Person(101, "Ashish", "M", "C"));
        pList.add(new Person(102, "Amit", "M", "C"));
        pList.add(new Person(103, "Ankit", "M", "H"));
        pList.add(new Person(104, "Radha", "F", "A"));
        pList.add(new Person(105, "Sunita", "F", "C"));
        pList.add(new Person(106, "Anuradha", "F", "A"));
        pList.add(new Person(107, "Anup", "M", "H"));
        pList.add(new Person(108, "Dipika", "F", "C"));
        pList.add(new Person(109, "Diksha", "F", "H"));
        pList.add(new Person(110, "Nirmal", "M", "C"));
        
        Collections.sort(plist,
                Comparator.comparing(Person :: getGender)
                        .thenComparing(Person ::getGamePrefrence)
                        .thenComparing(Person :: getName));
        System.out.println(plist);
    }
}

No comments:

Post a Comment