Java 集合和比较器

标签 java collections comparator

用例是对自定义对象列表进行排序的有效方式

class oC extends A{
  int id;
  ArrayList ocR;
}

class ocR extends A{
  @Override
  public int hashCode() {
    return super.hashCode();
  }

  @Override
  public boolean equals(Object o) {
    return super.equals(o);
  }
} 

oC 的每个对象的 ArrayList ocR 也必须按排序顺序。

目前的解决方案是我创建了一个实现比较器的排序函数

sort(List items){
  Collections.sort(items, new Comparator(){ //Logic for comparator by 
                                              overriding compare(A a, A b)} 
}

然后我使用下面的代码

List Oc comments;
for(int index=0;index<comments.size();index++){
   //This is for sorting ArrayList ocR of each oC object
   this.sort(comments.get(index).getocRs());
}
//This is for sorting List of oC
this.sort(comments);`

有没有办法在不在 oC 或 oCR 类上实现比较器的情况下取消 for 循环?

最佳答案

如果您使用的是 Java 8,您可以执行以下操作:

comments.forEach(oc -> sort(oc.getocRs()))

关于Java 集合和比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53518855/

相关文章:

java - 如何使用 gradle 创建的 fatJar 中存在的主要方法执行类

java - 从数据库列检索所有数据

java - PhantomJS 和 Selenium Webdriver - 如何清除 session

java - 上移、下移、指定位置

java - 想要使用比较器按时间戳对 ArrayList 中的聊天进行排序,但它不起作用,我不知道为什么

java - 按下按键后打印一行两次

java - 按字母顺序对复杂对象的数组列表进行排序

c# - 从列表集合中删除项目不删除

hadoop - 如何在 Hadoop 的 map-reduce 作业中通过自定义比较器对键进行排序?

java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 1 at beerregister. BeerRegister.list(BeerRegister.java:66)