I'm trying to solve an exercise from the book: Objects first with Java: A practical introduction using BlueJ.
The exercise goes as following:
Exercise 5.17 Rewrite the printEndangered method in your project to use Streams.
The original code is:
public void printEndangered(ArrayList<String> animalNames, int dangerThreshold)
{
for(String animal : animalNames) {
if(getCount(animal) <= dangerThreshold) {
System.out.println(animal + " is endangered.");
}
}
}
My attempt looks like this:
sightings.stream()
.filter(s -> animalNames.equals(s.getAnimal()))
.filter(s -> s.getCount() <= dangerThreshold)
.mapToInt(s -> s.getCount())
.forEach(s -> System.out.println(s));
The getCount()
method belongs to the class that contains printEndangered
, not to 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);
}