我有一组数据存储在HashMap中。数据中的元素进行比较,如果条件满足,则将其从元素中删除。但是,我正在使用for循环来迭代元素,它给我一个Java空指针错误。从HashMap中删除键值对在循环中给出错误
Example of comparisons:
Item: 0-1
Item: 0-2
Item: 0-3
Item: 0-4
Item: 1-2
Item: 1-3
Item: 1-4
Item: 2-3
Item: 2-4
Item: 3-4
Condition: IF Item 0-1 > (1-2, 1-3 and 1-4): store value 0-1 in another array
then remove Item 0-1, 1-2, 1-3 and 1-4 from HahsMap list. ELSE continue to next set
Condition: IF Item 0-2 > (2-3 and 2-4): store value 0-2 in another array
then removed Item 0-2, 2-3 and 2-4 from HahsMap list. ELSE continue to next set.
import java.util.HashMap;
import java.util.Map;
public class TestHashMapLoop {
public static void main(String[] args)
{
Map<String, Integer> myMap = new HashMap<String, Integer>();
myMap.put("0-1", 33);
myMap.put("0-2", 29);
myMap.put("0-3", 14);
myMap.put("0-4", 8);
myMap.put("0-5", 18);
myMap.put("1-2", 41);
myMap.put("1-3", 15);
myMap.put("1-4", 17);
myMap.put("1-5", 28);
myMap.put("2-3", 1);
myMap.put("2-4", 16);
myMap.put("2-5", 81);
myMap.put("3-4", 12);
myMap.put("3-5", 11);
myMap.put("4-5", 21);
int myMapCount = 6;
for(int i = 0; i < myMapCount; i++)
{
for(int j = i+1; j < myMapCount; j++)
{
String indexKey = i+"-"+j;
for(int k = 0; k < myMapCount; k++)
{
String compareKey = j+"-"+k;
System.out.println("Index " + indexKey + " : " + compareKey);
if((myMap.get(indexKey)) > (myMap.get(compareKey)))
{
//Store value indexKey in another array (not shown here)
System.out.println("Index" + myMap.get(compareKey) + " is removed..");
myMap.remove(compareKey);
}
System.out.println("Index " + myMap.get(indexKey) + " is removed..");
myMap.remove(indexKey);
}
}
}
}
}
任何人都可以提供建议,即使元素被删除或有更好的方法来做到这一点如何让循环回事?
什么是你想达到更好的办法?最终结果应该是什么样子?你为什么做这个?你是否想要对地图进行加权搜索? –
这是我试图让它工作的算法的一部分。我将值存储在HashMap中,因为我需要一种以某种方式迭代列表的方法。这是一种愚蠢的做法吗? – Cryssie
你是怎么决定你的'myMapCount'会是6? –