用 Java 中的 HashMap 中的匹配项填充数组

问题描述 投票:0回答:2

这是一个家庭作业,所以我必须使用数组。我知道使用 ArrayList 是更简单的解决方案,但不幸的是我不能。

我有一个动物的哈希图。我必须创建一个单独的数组并从 HashMap 中找到特定颜色的动物。所有匹配项都会放入数组中。

//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);
    }
  }
}

使用我当前的代码,我的数组被重复填充相同的动物,这是来自zooAnimals的最后一个匹配。一旦找到匹配项,如何让它移动到下一个数组索引?例如我的数组就像:

狗 狗 狗 狗 狗 狗 狗 狗 狗 狗

java arrays loops object hashmap
2个回答
1
投票
if(zooAnimals .get(key).getColor().equals("Brown"){
for(int i=0; i < animalArray.length; i++) {
  animalArray[i] = zooAnimals.get(key);
}

您已在颜色检查条件内定义了 for 循环。

  1. 最后匹配的动物仅在每次满足条件时覆盖数组时才会被存储。示例:每当
    animalArray[0]
    为 true
     时,都会为 
    zooAnimals.get(key).getColor().equals("Brown")
  2. 分配一个值
  3. 每次满足条件时,for 循环都会迭代 10 次,将值分配给索引 0-9 处的数组

for(字符串键:zooAnimals .keySet()){

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

0
投票

你可以更简单地使用流来解决这个问题:

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
© www.soinside.com 2019 - 2024. All rights reserved.