Reputation: 1
How would I go about printing all Animals
using a collection object:
Collection<Animal> c = animals.values();
I have already technically done it using entrySet however this is a more advanced way of doing it which isn't what i needed to do.
How would I go about Printing all animals using a collection object with a simple for each loop
Without using entrySets
?
Any help or advice on this would be much appreciated, thank you! :)
Zoo class:
public class MyZoo
{
private String zooId;
private int nextAnimalIdNumber;
private TreeMap<String, Animal> animals;
private Animal animal;
public MyZoo(String zooId)
{
this.zooId = zooId.trim().substring(0,3).toUpperCase();
nextAnimalIdNumber = 0;
animals = new TreeMap<String, Animal>();
}
public void addAnimal(Animal animal)
{
animals.put(animal.getName(), animal);
this.animal = animal;
}
public void printAllAnimals()
{
Collection<Animal> c = animals.values();
}
}
Animal class:
public class Animal
{
private String id;
private String species;
private String name;
public Animal(String species, String name, MyZoo owner)
{
id = owner.allocateId();
this.species = species;
this.name = name;
}
public String getId()
{
return id;
}
public String getName()
{
return name;
}
public String getSpecies()
{
return species;
}
public String toString()
{
return id + " " + name + ": a " + species;
}
}
Upvotes: 0
Views: 653
Reputation: 308948
You can use a for loop:
for (Animal a: animals) {
System.out.println(a);
}
I'd prefer being more succinct: use a lambda.
animals.stream().forEach(System.out::println);
Upvotes: 1
Reputation: 54168
Using Streams
:
public void printAllAnimals(){
animals.values().stream().forEach(System.out::println);
}
Using classic for each loop
public void printAllAnimals(){
for (Animal ani: animals.values()) {
System.out.println(ani);
}
}
Upvotes: 0