Java sort object by list type property

后端 未结 5 451
北海茫月
北海茫月 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:54

    You can define new Comparator to define your sort criteria like this:

    Comparator shippingComparator = new Comparator{
    public int compare(Shipping obj1, Shipping obj2) {
        //your rules for comparing Shipping1, Shipping 2 goes here
        //return -1 when obj1 should be before obj2
        //return 1 when obj1 should be after obj2
        //return 0 when obj1 is equal to obj2 and relative position doesnt matter
    } 
    

    Then use this comparator to sort your List:

    ArrayList shippings;
    //populate List
    Collections.sort(shippings, shippingComparator );
    

提交回复
热议问题