Java sort object by list type property

后端 未结 5 537
北海茫月
北海茫月 2021-01-27 14:24

I have the following objects:

public class Shipping {
    String name;
    List methods;
}

public class Method {
    String serviceType;
    Strin         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-01-27 14:56

    You need either a comparator or implement Comparable for Method class like:

    public class Method implements Comparable {
        public int compareTo(Method thatMethod) {
            return Integer.compare(Integer.parseInt(this.cost), Integer.parseInt(thatMethod.getCost()));//if you need name then you could do this.cost.compareTo(thatMethod.getServiceType()); assuming serviceType can never be null 
        }
    }
    

    And then sort your list like:

    Collections.sort(methods);
    

提交回复
热议问题