我有一组存储在 HashMap 中的数据。比较数据中的元素,如果满足条件,则将它们从元素中删除。但是,我使用 for 循环来迭代元素,它给了我一个 Java Null Pointer 错误。
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);
}
}
}
}
}
任何人都可以建议即使元素被删除,如何让循环继续进行,还是有更好的方法来做到这一点?