这是一个家庭作业,所以我必须使用数组。我知道使用 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的最后一个匹配。一旦找到匹配项,如何让它移动到下一个数组索引?例如我的数组就像:
狗 狗 狗 狗 狗 狗 狗 狗 狗 狗
if(zooAnimals .get(key).getColor().equals("Brown"){
for(int i=0; i < animalArray.length; i++) {
animalArray[i] = zooAnimals.get(key);
}
您已在颜色检查条件内定义了 for 循环。
animalArray[0]
为 true时,都会为
zooAnimals.get(key).getColor().equals("Brown")
for(字符串键:zooAnimals .keySet()){
for(String key: zooAnimals .keySet()){
int index=0;
if(zooAnimals .get(key).getColor().equals("Brown"){
animalArray[index] = zooAnimals.get(key);
index++;
}
}
你可以更简单地使用流来解决这个问题:
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