简体   繁体   中英

Java Comparator - Comparing 2 different objects in list

I have following class in Java, and I want to compare the tocompare objects in list with the previous tocompare object ie compare t2 to t1 .

I am new to Java, so I don't have much knowledge about How to do this.

public class ToCompare {
    private String property1;
    private String property2;

    public void getProperty1(){
        return property1;
    }
    public void setProperty1(String property1){
        this.property1 = property1;
    }

    public void getProperty2(){
        return property2;
    }
    public void setProperty1(String property2){
        this.property2 = property2;
    }
}

List<ToCompare> tocompare = new ArrayList();
ToCompare t1 = new ToCompare();
ToCompare t2 = new ToCompare();
ToCompare t3 = new ToCompare();
ToCompare t4 = new ToCompare();

tocompare.add(t1); //obj1
tocompare.add(t2); //obj2
tocompare.add(t3); //obj3
tocompare.add(t4); //obj4

for (String comp : tocompare) {
    // compare properties of 2nd ToCompare object with 1st ToCompare object
}

Use Comparable interface and implement the compareTo method which defines the comparison strategy - https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

For example, if you want to compare them based on property1 -

public class ToCompare implements Comparable<ToCompare> {
    private String property1;
    private String property2;

    public void getProperty1(){
        return property1;
    }

    public void setProperty1(String property1){
        this.property1 = property1;
    }

    public void getProperty2(){
        return property2;
    }

    public void setProperty1(String property2){
        this.property2 = property2;
    }

    @Override
    public int compareTo(ToCompare toCompare){  
        return this.getProperty1().compareTo(i.getProperty1()); 
   }  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM