我有以下对象:
public class Shipping {
String name;
List<Method> methods;
}
public class Method {
String serviceType;
String cost;
}
我有:
List<Shipping> shippings;
我想按返回最便宜费用的方法对运输进行排序。
示例:
shipping: "Josh" with 2 methods: "Premium","5" and "Basic","3"
shopping: "Nash" with 2 methods: "Prem", "7" and "Base","2"
将像这样排序:
shopping: "Nash" with 2 methods: "Base","2" and "Prem", "7"
shopping: "Josh" with 2 methods: "Basic","3" and "Premium","5"
我需要它返回方法成本最便宜的方法作为第一个方法,同时也将方法排序为最便宜的方法。
最好的方法是什么?我正在使用 Java 8,如果它有更好的解决方案,并且有 guava 库
编辑: 成本是一个 float 。我需要将其保留为 String,因为它是我传递给 REST api 的对象,并且不希望客户端解析它。
最佳答案
我们假设所有运输至少有一种方法。因此您希望运输方式按成本排序。那么让我们这样做:
shippings.forEach(shipping -> {
shipping.getMethods().sort(Comparator.comparing(Method::getCost));
});
然后您希望按照最低成本的方法对运输列表进行排序。最低成本是第一种方法的成本,因为它们现在已排序:
shippings.sort(Comparator.comparing(shipping -> shipping.getMethods().get(0).getCost()));
请注意,这假设您希望按字典顺序比较成本。正如我怀疑的那样,如果成本实际上是一个数字,那么它应该像这样存储在 Method 类中,而不是作为字符串存储。因此,请将其设为 Integer 或 BigDecimal,或任何适当的类型。
关于Java按列表类型属性对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30465353/