Comparator using a String field of my class for comparison?

别等时光非礼了梦想. 提交于 2021-01-28 12:00:55

问题


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?


回答1:


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



回答2:


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.




回答3:


You could use String compareTo



来源:https://stackoverflow.com/questions/6890006/comparator-using-a-string-field-of-my-class-for-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!