I've trying to figure out this exercise in the book Objects First with Java for a couple of hours, not managing to understand several aspects.
The exercise reads: Rewrite the printEndangered method in your project to use streams. Test. (To test this method, it may be easiest to write a test method that creates an ArrayList of animal names and calls the printEndangered method with it.)
/**
* Print a list of the types of animal considered to be endangered.
* @param animalNames A list of animals names.
* @param dangerThreshold Counts less-than or equal-to to this level
* are considered to be dangerous.
*/
public void printEndangered(ArrayList<String> animalNames,
int dangerThreshold)
{
for(String animal : animalNames) {
if(getCount(animal) <= dangerThreshold) {
System.out.println(animal + " is endangered.");
}
}
}
/**
* Return a count of the number of sightings of the given animal.
* @param animal The type of animal.
* @return The count of sightings of the given animal.
*/
public int getCount(String animal)
{
return sightings.stream()
.filter(sighting -> animal.equals(sighting.getAnimal()))
.map(sighting -> sighting.getCount())
.reduce(0, (runningSum, count) -> runningSum + count);
}
At the start of this chapter I was asked to test out the methods of this class, but the printEndangered-method I didn't get to work. I did not understand what to put in the parameter field of the ArrayList-parameter, and so now I can't manage to write this method.
How do you use an ArrayList as a parameter? What do they mean by write a test method that creates an ArrayList of animal names? How will I go forth writing this method?
Edit: This code is already written for me in a project provided by the author of the book. I got a great hint by you asking for the getCount code, but I'm still a bit confused as to what I should do with the ArrayList-parameter. It is in BlueJ and I haven't managed to make the original method work because I don't understand what I should write in the field asking for the ArrayList-parameter. Should I make a method that makes an ArrayList which returns that to the printEndangered-method? The only way I can think of is to make a different method that checks animalcount, collects the names of those animals and prints those, but the thing about the test-method and ArrayList still bogs me.
Comments
Post a Comment