Jared Garrett
Jared Garrett

Reputation: 1

How to print all Animals using Collection Object

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

Answers (2)

duffymo
duffymo

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

azro
azro

Reputation: 54168

  1. Using Streams :

    public void printAllAnimals(){
        animals.values().stream().forEach(System.out::println); 
    }
    
  2. Using classic for each loop

    public void printAllAnimals(){
        for (Animal ani: animals.values()) {
            System.out.println(ani);
        }
    }
    

Upvotes: 0

Related Questions