2013-10-31 74 views
1

我有一個持有學生對象如下的ArrayList:從一個鍵移動值到另一個HashMap中

List<Students> stdList = new ArrayList<Students>(); 
stdList.add(new Students(1,"std1","address1")); 
stdList.add(new Students(2,"std2","address2")); 
stdList.add(new Students(3,"std3","address3")); 
stdList.add(new Students(4,"std4","address4")); 
stdList.add(new Students(5,"std5","address5")); 
stdList.add(new Students(6,"std6","address6")); 
stdList.add(new Students(7,"std7","address7")); 
stdList.add(new Students(8,"std8","address8")); 

現在,我需要將stdList劃分含等於沒有學生說的兩組4在這種情況下,並將它們添加到HashMap中我實現:

int j=0; 
HashMap<Integer,List<Students>> hm = new HashMap<>(); 
    for (int i = 0; i < stdList.size(); i = i + 4) 
    { 
    j++; 
    hm.put(j,stdList.subList(i, i + 4)); 

    } 

HashMap中現在包含密鑰值對爲:

{1=[1 std1 address1, 2 std2 address2, 3 std3 address3, 4 std4 address4], 2=[5 std5 address5, 6 std6 address6, 7 std7 address7, 8 std8 address8]} 

現在我需要移動一個值,說「3 STD3地址3」,從「密鑰1」至「密鑰2」,如:

{1=[1 std1 address1, 2 std2 address2, 4 std4 address4], 2=[5 std5 address5, 6 std6 address6, 7 std7 address7, 8 std8 address8,3 std3 address3]} 

我怎樣才能做到這一點?

+0

是否要合併值或覆蓋? – MadConan

+2

您是否在大規模數據中詢問搜索算法,或者直接詢問如何更改HashMap中的條目? – Dropout

回答

0
List<Student> ls = hm.get(1); 
Student st = ls.get(3); 
ls.remove(st); hm.get(2).add(st); 

如果您可以通過索引訪問它,則不需要搜索列表。

1

假設「someKey」是你的關鍵要刪除,然後

key1.put(someKey, key2.remove(someKey)); 
0

的解決辦法是得到HashMap的學生名單,並刪除您要移動的Student對象。然後從HashMap中獲取另一個列表,只需添加該對象即可。

我沒有運行下面的代碼,但它會是這樣的

//Get the list for Key 1 
List<Students> list = hm.get(Integer.valueOf(1)); 

//Remove the 3rd value, that would be your "3 std3 address3" 
Students std = list.remove(2); 

//Now get the list of Key 2 
list = hm.get(Integer.valueOf(2)); 

//Add the value to that list 
list.add(std); 
+0

刪除(3)將刪除第四名學生我的兄弟:P –

+0

woops,修復它。 –

0

你可以這樣做;

Student stud3=myMap.get(1).remove(myMap.get(1).get(2)); 
List<Student> secondList=myMap.get(2); 
secondList.add(stud3); 
myMap.put(2,secondList); 

其中myMap是由您組成的地圖。

0

我想你知道如何搜索列表/地圖中的元素,以及如何刪除/添加它們。您已在代碼中顯示它。您的需求只是這些方法調用的另一個組合,它們不會對您造成問題。

你不能走的更遠,因爲你有一個例外:

ConcurrentModificationException 

因爲我看到你已經使用subList()方法。它將返回支持列表的視圖。您可以更改該列表中的元素,但任何結構修改都會拋出該異常。

如果這是你面臨的問題,簡單的解決方案將創建一個新的列表,當你調用subList,如new ArrayList(stdList.subList(i, i + 4))然後你可以做結構修改。

如果這不是你的問題,請留下評論,我會刪除答案。

PS你可能想改變你的數據結構,我不知道你的具體要求,但目前的結構不是那麼方便.....你可以查看番石榴多圖...

相關問題