打印低于阈值的动物总数
Printing the sum of animals that are below a threshold
我正在尝试解决书中的一个练习:Objects first with Java:使用 BlueJ 的实用介绍。
练习如下:
Exercise 5.17 Rewrite the printEndangered method in your project to use 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));
getCount()
方法属于包含printEndangered
的class,不属于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);
}
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"));
我正在尝试解决书中的一个练习:Objects first with Java:使用 BlueJ 的实用介绍。
练习如下:
Exercise 5.17 Rewrite the printEndangered method in your project to use 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));
getCount()
方法属于包含printEndangered
的class,不属于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);
}
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"));