【问题标题】:Java <Streams> How to sort the list of my objects, based on the count of the components of the ListJava <Streams> 如何根据列表的组件数对我的对象列表进行排序
【发布时间】:2018-03-18 16:22:09
【问题描述】:

我有 2 个 Java 课程。一个是由 5 个变量组成的 Car 类。其中我有一个 List 设备变量。另一个类包含 Car 类对象的列表:List carlist。

我的任务是:我必须根据给定汽车拥有的设备数量使用 Java 中的 Streams 对汽车对象列表进行排序。

我该怎么做?我试图构建一个单独的方法来计算对象列表中的项目 - 但是在比较器中我不能将对象作为该方法的参数。

这是我的代码的摘录:

private int countEquipmentItems (Car s){
    if (s == null){
        return 0;
    }
    int countEquipment = 0;
    List<String> a = s.getEquipment();
    for (int i = 0; i <a.size() ; i++) {
        countEquipment ++;
    }
    return countEquipment;
}

我已经尝试在 Stream 中使用这种方法:

public void sortbyEquipment (List<Car> carList){
    carList.stream()
            .sorted(Comparator.comparing(countEquipmentItems(Car s)));
    }
}

感谢您的帮助

【问题讨论】:

  • 你必须使用流吗?对列表进行适当的排序会更有意义。
  • 你自己有没有想过for (int i = 0; i &lt;a.size() ; i++) { countEquipment ++; } 是一种冗长的表达方式countEquipment += a.size();
  • 是的,我必须使用流——这是练习的一部分。至于第二条评论 - 是的,既然您指出了这一点,那就很明显了。对不起 - 菜鸟错误

标签: java java-8 java-stream


【解决方案1】:

您不需要countEquipmentItems 方法来计算设备数量。只需使用car.getEquipment().size()

public void sortbyEquipment (List<Car> carList){
    carList.stream()
           .sorted(Comparator.comparing(car -> car.getEquipment().size()))
           ...
}

当然,您可以将Comparator 直接传递给Collections.sort(),这样就可以对列表进行排序,而无需创建Stream

【讨论】:

    【解决方案2】:

    您的countEquipmentItems 方法是多余的,完全没有必要。

    Eran 提供的另一种解决方案是调用可用于List&lt;T&gt; 类型的默认sort 方法。

    carList.sort(Comparator.comparingInt(car -> car.getEquipment().size()));
    

    或者,如果您希望已排序的项目位于新集合中,那么您可以这样做:

    List<Car> clonedList = new ArrayList<>(carList); // clone the carList
    clonedList.sort(Comparator.comparingInt(car -> car.getEquipment().size()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      • 2019-02-11
      • 2013-12-01
      • 1970-01-01
      • 2012-05-19
      • 2023-04-01
      相关资源
      最近更新 更多