-1

It's for a homework assignment so I have to use an Array. I understand using an ArrayList would be the easier solution, but unfortunately I can't.

I have a HashMap of animals. I have to create a separate Array and find the animals from the HashMap that are a certain color. All of the matches will get put into the Array.

//This Hashmap is already filled with Animals
zooAnimals = new HashMap<>();
//This array needs to be filled with the matches
Animal[] animalArray = new Animal[10];

for(String key: zooAnimals .keySet()){
  for(int i=0; i < animalArray.length; i++) {
    if(zooAnimals .get(key).getColor().equals("Brown"){
      animalArray[i] = zooAnimals.get(key);
    }
  }
}

With my current code, my Array is being being repeatedly filled with the same animal which is the last match from zooAnimals. how do I get it to move onto the next Array index once the match is found? For example my array is just like:

Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog

4
  • 1
    Your code is replacing every item in the animal array with the newest zooAnimals.get(key) every time your outer for loop runs. Walk through it in your mind to see this is so. Myself, I would filter the map using a stream, and then have the stream create an array. Commented Oct 23, 2023 at 21:36
  • What your code does is replace unconditionally every entry of animalArray with the last "Brown" animal. If after a dog, you had a bear, also brown, all entries would be "Bear". Surely not what you want to accomplish. Have a beer and try again. Commented Oct 23, 2023 at 21:46
  • tea or coffee, not beer Commented Oct 23, 2023 at 21:47
  • @HovercraftFullOfEels "tea or coffee, not beer", let's call it a creative break ;-) . Commented Oct 23, 2023 at 21:49

4 Answers 4

1
if(zooAnimals .get(key).getColor().equals("Brown"){
    for(int i=0; i < animalArray.length; i++) {
        animalArray[i] = zooAnimals.get(key);
    }
}

You have your for-loop defined inside the colour check condition.

  1. The last matched animal is only being stored as you are overriding the array each time the condition is met. Example: animalArray[0] will be assigned a value every time zooAnimals.get(key).getColor().equals("Brown") is true
  2. The for-loop is iterating 10 times each time the condition is met assigning values to array at index 0-9

int index=0;
for(String key: zooAnimals .keySet()){
    if(zooAnimals .get(key).getColor().equals("Brown"){
        animalArray[index] = zooAnimals.get(key);
        index++;
    }
}       
Sign up to request clarification or add additional context in comments.

2 Comments

With the declaration of index inside the loop you might as well just use animalArray[0].
Happy to help. Can you accept this as answer?
1

You can more simply use streams to solve this problem:

String color = "brown";
Animal[] animals = zooAnimals
        .values()  // get a collection of the map's values 
        .stream()  // convert it into a stream      
        // filter stream to gather only animals of a certain color
        .filter(animal -> animal.getColor().equalsIgnoreCase(color))
        .toArray(Animal[]::new); // collect the stream into an array of animals

Here is a runnable example:

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class TestAnimals {
    public static void main(String[] args) {
        Map<String, Animal> zooAnimals = new HashMap<>();

        // fill a map with a bunch of animals
        zooAnimals.put("Lion", new Animal("Lion", "Yellow"));
        zooAnimals.put("Tiger", new Animal("Tiger", "Orange"));
        zooAnimals.put("Bear", new Animal("Bear", "Brown"));
        zooAnimals.put("Penguin", new Animal("Penguin", "Black"));
        zooAnimals.put("Panda", new Animal("Panda", "Black and White"));
        zooAnimals.put("Polar Bear", new Animal("Polar Bear", "White"));
        zooAnimals.put("Giraffe", new Animal("Giraffe", "Yellow"));
        zooAnimals.put("Elephant", new Animal("Elephant", "Gray"));
        zooAnimals.put("Horse", new Animal("Zebra", "Brown"));
        zooAnimals.put("Monkey", new Animal("Monkey", "Brown"));
        zooAnimals.put("Kangaroo", new Animal("Kangaroo", "Brown"));
        zooAnimals.put("Koala", new Animal("Koala", "Gray"));
        zooAnimals.put("Crocodile", new Animal("Crocodile", "Green"));
        zooAnimals.put("Snake", new Animal("Snake", "Green"));
        zooAnimals.put("Turtle", new Animal("Turtle", "Green"));

        Animal[] brownAnimals = getAnimalsByColor(zooAnimals, "Brown");

        System.out.println(Arrays.toString(brownAnimals));
    }

    public static Animal[] getAnimalsByColor(Map<String, Animal> zooAnimals, String color) {
        Animal[] animals = zooAnimals.values().stream()
                .filter(animal -> animal.getColor().equalsIgnoreCase(color))
                .toArray(Animal[]::new);
        return animals;
    }
}
class Animal {
    private String name;
    private String color;

    public Animal(String name, String color) {
        this.name = name;
        this.color = color;
    }

    // getters
    public String getName() {
        return name;
    }

    public String getColor() {
        return color;
    }

    // tostring
    @Override
    public String toString() {
        return "Name: " + name + ", Color: " + color;
    }

}

Comments

0

I assume you have all right in the Animal class

 // a List to store animals
    List<Animal> animalList = new ArrayList<>();   

 // Sort HashMap to find animals with the specified color
    for (Animal animal : zooAnimals.keyset()) {
        if (animal.getColor().equals("Brown")) {
            animalList.add(animal);
        }
    }

//then if you want convert list to array
Animal[] animalArray = animalList.toArray(new Animal[animalList.size()]);

Let me know if it works

Comments

0

"... I have a HashMap of animals. I have to create a separate Array and find the animals from the HashMap that are a certain color. All of the matches will get put into the Array. ..."

Use the Map#values method, instead.

Animal[] animalArray = new Animal[0];

for (Animal a : zooAnimals.values())
    if (a.getColor().equals("Brown")) {
        animalArray = Arrays.copyOf(animalArray, animalArray.length + 1);
        animalArray[animalArray.length - 1] = a;
    }

Optionally, use a stream.

Animal[] animalArray
    = zooAnimals.values()
                .stream()
                .filter(x -> x.getColor().equals("Brown"))
                .toArray(Animal[]::new);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.