简体   繁体   中英

Comparator using a String field of my class for comparison?

I have a list of objects of type A, and I have to order it for a field of A, which is of type String.

public class A{
    public String field1;
    public Integer field2;
    ...
}

If I had to order for the int field would have done so:

Collections.sort(listOfA, new Comparator<A>() {
        public int compare(A p1, A p2) {
            return p1.field2 - p2.field2);
            }
        });

But unfortunately need to order by the field of type String.

How can I do this?

    public int compare(A p1, A p2) {
        return p1.field2.compareTo( p2.field2) );
        }

Alternatively your class could implement interface Comparable , like this

public class A implements Comparable<A> {
  public String field1;
  public Integer flied2;

    public int compareTo(A o) {
        return this.field1.compareTo(o.field1);
    }

}

Which would allow you to

Collections.sort(listofA);

Which IMO is preferable/cleaner if A's are always sorted by field1.

你可以使用 String compareTo

Old thread, nevertheless.
With java 8, you now have lambdas:

listOfA.sort((a,b) -> a.field1.compareTo(b.field1));

Also, if one had a getter for field1, which one probably should, you could also then do

listOfA.sort(Comparator.comparing(A::getFieldOne));

If you don't have a getter, there's also this:

listOfA.sort(Comparator.comparing(a -> a.field1));

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