我有一組數據存儲在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? –