我有一个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。我如何获得列表中的所有值,而不是被新值覆盖。任何帮助。
答案 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);