How to use Java Comparator to compare objects


The comparator can be used to compare two user-defined objects. You can use it to compare objects and sort. Please look at the following example. 

Using Comparator in Java 7

Laptop.java

package com.app.comparator;

public class Laptop {

    private String model;
    private Integer price;
    private Integer memory;

    @Override
    public String toString() {
        return "Laptop{" +
                "model='" + model + '\'' +
                ", price=" + price +
                ", memory=" + memory +
                '}';
    }

    public Laptop(String model, Integer price, Integer memory) {
        this.model = model;
        this.price = price;
        this.memory = memory;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    public Integer getMemory() {
        return memory;
    }

    public void setMemory(Integer memory) {
        this.memory = memory;
    }
}


CompareDemo.java

package com.app.comparator;

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

public class ComparatorDemo {

    public static void main(String args[]) {

        List<Laptop> list = new ArrayList<>();
        list.add(new Laptop("Apple", 300, 2));
        list.add(new Laptop("Dell", 100, 5));
        list.add(new Laptop("Asus", 200, 7));

        Comparator<Laptop> com = new Comparator<Laptop>() {
            @Override
            public int compare(Laptop o1, Laptop o2) {
                if (o1.getMemory() > o2.getMemory())
                    return 1;
                else
                    return -1;
            }
        };

        Collections.sort(list, com);
        System.out.println(list);
    }
}


In this example, I compared Laptop objects using their memory. You can use compare any field with your requirements. If you want to order in reverse order, you can use it like below.

Collections.sort(list, com.reversed());



Using comparator with Java 8 lambda expressions

//      Using Java 8 lambda expressions
        list.sort((Laptop l1, Laptop l2) -> l1.getMemory()-l2.getMemory());
        System.out.println(list);


Using comparator with Java 8 methods reference

//      Using Java 8 methods references
        list.sort(Comparator.comparingInt(Laptop::getMemory));
        System.out.println(list);




How to use Java Comparator to compare objects How to use Java Comparator to compare objects Reviewed by Ravi Yasas on 10:33 PM Rating: 5

No comments:

Powered by Blogger.