JAVA - 如何通过比较列表中的多个值来使用比较器对对象列表进行排序

标签 java list sorting comparator

我对 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/

相关文章:

java - 为什么 Hibernate 生成一个连接错误列的查询?

python - 用字符串填充空列表元素python

list - Lisp 循环列表

python - 对键也是字典的字典键进行排序

java - JasperReport JRDesign 实现

java - 如何设置正确的结构缓冲区大小?

java - 是否可以在 onSaveInstanceState 中保存 Stack<Stack<View>>

python - 需要更好的逻辑来将字符串的每个第 i 个字符与其反向字符串的每个第 i 个字符相加

java - 将对象类型和字段传递给比较器

javascript - 数据表日期排序(DD.MM.YYYY.)格式