簡體   English   中英

創建其他地圖

[英]Create a map of another map

我有一個看起來像這樣的地圖:

Map<String, List<Integer>> map = new TreeMap<>();

可以說地圖的內容如下:

one, [-55, -55, -54, -54, -55, -54, -54, -54, -54, -55]
two, [-61, -61, -61, -61, -60, -61, -60, -61, -60, -60]
three, [-69, -69, -68, -68, -68, -69, -70, -68, -69, -69]

我創建了一個名為“ addRandomValuesToList”的方法,該方法查看一個稱為input的整數列表,采用4個值並將它們放入另一個名為randomValues的列表中。

public static List<Integer> addRandomValuesToList(List<Integer> input) 
{
    List<Integer> randomValues = new ArrayList<>();
    ...
    return randomValues 
}

我想在地圖上的所有列表上使用addRandomValuesToList方法,因此得到例如:

one, [-54, -54, -54, -54]
two, [-61, -61, -61, -61,]
three, [-69 -69, -70, -68]

我很難做到這一點。 我嘗試了類似的東西:

Map<String, List<Integer>> test = new TreeMap<>();

for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
     newList = addRandomValuesToList(entry.getValue());
     test.put(entry.getKey(), newList);
}

這將導致測試圖中的某些列表完全為空。 我做錯了什么還是我的方法做錯了?

應該將變量聲明為局部變量。 (它將只在一個循環中存儲一次內存。)

Map.Entry也由地圖的內部數據支持。 因此它有一個setValue方法,盡管不是setKey

Map<String, List<Integer>> test = new TreeMap<>();
for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
     List<Integer> newList = addRandomValuesToList(entry.getValue());
     entry.setValue(newList);
}

同樣, getValue列表是來自地圖的內部數據,由地圖支持。 一個可以做:

entry.getValue().add(42);

addRandomValuesToList :如果確實修改了傳遞的條目值,則該方法可以為空,無需對結果做任何事情。

關於錯誤,我不確定。 映射中的每個列表都必須是一個新實例( new ArrayList<>()等)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM