迭代循环以获取字符串列表并存储元素值

时间:2016-12-06 07:34:08

标签: java loops arraylist iterator

我有一个hashmap,其中包含我在for loop.中进行交互的键列表 在我的Hashmap中,我有一个键FURNITURE_NAMES,值为Table,Chair,Board. 现在我希望FURNITURE_NAMES的密钥中存在的值存储在列表中。

以下是我所做的代码:

当我获得密钥FURNITURE_NAMES时,我有以下值

FURNITURE_NAMES =“桌子,椅子,板子”

for(Map.Entry<String, List<String>> entry : furnitureMap.entrySet()) 
{
String furnitureKey = entry.getKey();
for(String key : entry.getValue() )
    {   
    if(furnitureKey!=null && furnitureKey.equalsIgnoreCase("FURNITURE_NAMES"))
        {                           
            furnitureList = new ArrayList<String>();
            String a = new String();
            a=key;
            furnitureList.add(a);                                                       
        }
    }
}

当我迭代Hashmap时,获取密钥FURNITURE_NAMES我得到第一个值"Table" 该值存储在列表中。 第二,我得到chair。 它覆盖了值表,我在列表中只有chair只有一个值。

我试图通过索引将值放在列表中,但它抛出了indexoutofboundsexception。我如何获得列表中的所有值,而不是被新值覆盖。任何帮助。

3 个答案:

答案 0 :(得分:2)

在每次迭代中,您将按如下方式创建列表的新实例:

furnitureList = new ArrayList<String>();

您必须在for或其他地方之前创建此列表,并保留如下:

furnitureList = new ArrayList<String>();
for(Map.Entry<String, List<String>> entry : furnitureMap.entrySet()) {
// same code here except the list initialization
}

此外,您不需要为每个值创建新的String。只需将它作为for循环中的值变量(错误地命名为key :))放在列表​​中。如果我们重构您的代码,它将类似于:

furnitureList = new ArrayList<String>();
for(Map.Entry<String, List<String>> entry : furnitureMap.entrySet()) {
    if(entry.getKey() != null && entry.getKey().equalsIgnoreCase("FURNITURE_NAMES")) {
        furnitureList.addAll(entry.getValue());
    }
}

答案 1 :(得分:1)

对于您正在进行的每次迭代

furnitureList = new ArrayList<String>();

重新初始化您的列表。

将其移至第一个for循环

之前

e.g。

furnitureList = new ArrayList<String>();
for(Map.Entry<String, List<String>> entry : furnitureMap.entrySet()) 

答案 2 :(得分:-2)

应该是,应该在迭代map值(即列表)之前创建list,并且不需要创建字符串a,它可以直接添加到列表中,或者你想克隆尝试{{1} }

String newKey=new String(key);