Java sort object by list type property

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

    We will assume all the shippings have at least 1 method. So you want the methods of the shippings to be sorted by cost. So let's do that:

    shippings.forEach(shipping -> {
        shipping.getMethods().sort(Comparator.comparing(Method::getCost));
    });
    

    Then you want the list of shippings to be sorted by the lowest cost of their methods. The lowest cost is the cost of the first method, since they're now sorted:

    shippings.sort(Comparator.comparing(shipping -> shipping.getMethods().get(0).getCost()));
    

    Note that this assumes that you want the costs to be compared lexicographically. If, as I suspect, the cost is in fact a number, then it should be stored as such in the Method class, and not as a String. So make it an Integer or a BigDecimal, or whatever the appropriate type is.

提交回复
热议问题