我对 Java 比较器有疑问。或者也许你们都有另一个想法来解决这个问题。
我有一个名为 Product 的对象,在 Product 类下面看起来像:
public class Product(){
private String productId;
private List categoryList;
//...setter and getter for category List
}
然后我有一个产品列表,List。我想根据产品类别对列表进行排序:
这里是列表示例:
{
Product = {
productId:10000567,
categoryList: {1002, 1003, 1007}
},
Product = {
productId:10000568,
categoryList: {1001, 1003, 1007}
},
Product = {
productId:10000569,
categoryList: {1001, 1004, 1007}
},
Product = {
productId:10000570,
categoryList: {1004, 1005, 1007}
}
}
我已经尝试使用比较器,但我只能比较一个值一次。 感谢您的回复。
最佳答案
首先,让你的Product类实现Comparable接口(interface),然后实现compareTo(),然后用Collections.sort(myList)对List进行排序;
public class Product implements Comparable<Product>{
private String productId;
private List categoryList;
//...setter and getter for category List
public int compareTo(Product p) {
//return -1, 0 or 1 based on what you decide makes p to be less than this
}
}
//sort it
java.util.Collections.sort(myProductList);
关于JAVA - 如何通过比较列表中的多个值来使用比较器对对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8428033/