Java sort object by list type property

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

    You can first sort the methods field of each Shipping instance in your shippings list, then sort the shippings list by the first element of each instance's methods list:

    for (Shipping shipping : shippings)
        shipping.methods.sort((m1, m2) -> Integer.compare(m1.cost, m2.cost));
    
    shippings.sort((s1, s2) -> 
      Integer.compare(s1.methods.get(0).cost, s2.methods.get(0).cost));
    

    You might have to do a little extra work converting the costs to integers, but the overall idea is the same.

提交回复
热议问题