【问题标题】:Printing the sum of animals that are below a threshold打印低于阈值的动物总数
【发布时间】:2018-04-03 20:32:17
【问题描述】:

我正在尝试解决书中的一个练习:Objects first with Java:使用 BlueJ 的实用介绍。

练习如下:

练习 5.17 重写项目中的 printEndangered 方法以使用 Streams。

原代码为:

public void printEndangered(ArrayList<String> animalNames, int dangerThreshold)
{
    for(String animal : animalNames) {
        if(getCount(animal) <= dangerThreshold) {
            System.out.println(animal + " is endangered.");
        }
    }
}

我的尝试如下所示:

sightings.stream()
    .filter(s -> animalNames.equals(s.getAnimal()))
    .filter(s -> s.getCount() <= dangerThreshold)
    .mapToInt(s -> s.getCount())
    .forEach(s -> System.out.println(s));

【问题讨论】:

  • sightings是什么,和原代码有什么关系?
  • Sightings 是一个 ArrayList,其中包含作为 Sighting 类的对象的目击事件。其中包含已进行的不同目击的信息。您可以在此处下载项目文件:bluej.org/objects-first/resources/projects.zip 它来自第 5 章:Animal-monitoring-v1
  • getCount 是做什么的?这条线很奇怪:.filter(s -&gt; animalNames.equals(s.getAnimal()))。您正在将数组列表与动物对象进行比较?

标签: java lambda functional-programming java-stream bluej


【解决方案1】:

getCount() 方法属于包含printEndangered 的类,而不属于s

public void printEndangered(ArrayList<String> animalNames, int dangerThreshold) {
    animalNames.stream()
               .filter(animal -> getCount(animal) <= dangerThreshold)
               .map(animal -> animal + " is endangered.")
               .forEach(System.out::println);
}

【讨论】:

    【解决方案2】:
    sightings.stream()
    //.filter(s -> animalNames.equals(s.getAnimal())) -- not required
    .filter(s -> getCount(s) <= dangerThreshold)
    //.mapToInt(s -> s.getCount()) -- not required
    .forEach(s -> System.out.println(s + " is Endangered"));
    

    【讨论】:

    • getCount() 完全不同的签名?
    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 2023-01-30
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2018-11-19
    相关资源
    最近更新 更多