按列表类型属性的Java排序对象

我有以下对象:

public class Shipping { String name; List methods; } public class Method { String serviceType; String cost; } 

我有:

 List 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

编辑:成本是一个浮点数。 我需要将它保留为String,因为它是一个传递给REST api的对象,并且不希望客户端解析它。

我们假设所有的发货都至少有一种方法。 因此,您希望按照成本对发货方法进行排序。 所以我们这样做:

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

然后,您希望按照其方法的最低成本对发货列表进行排序。 最低成本是第一种方法的成本,因为它们现在已经分类:

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

请注意,这假设您希望按字典顺序比较成本。 如果,正如我怀疑的那样,成本实际上是一个数字,那么它应该存储在Method类中,而不是作为String存储。 所以把它变成一个Integer或BigDecimal,或者任何合适的类型。

您需要比较器或实现Comparable for Method类,如:

 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 } } 

然后对列表进行排序,如:

 Collections.sort(methods); 

您可以定义新的Comparator来定义您的排序条件,如下所示:

 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 } 

然后使用此比较器对List进行排序:

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

您可以先在shippings列表中对每个Shipping实例的methods字段进行排序,然后按每个实例的methods列表的第一个元素对shippings列表进行排序:

 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)); 

您可能需要做一些额外的工作将成本转换为整数,但总体思路是一样的。

我建议您阅读Java的订购教程 。 您的要求似乎表明您希望按其Method对每个Shipping实例进行排序,以及您希望对按字母顺序排序的Shipping实例集合进行排序的其他位置,但是您不完全清楚自己编写的内容。

无论如何,一旦您阅读本教程,这很容易做到。 总之,您可以使用Comparator或实现Comparable ,只需在数据集上调用Collections.sort(…)。