簡體   English   中英

在 HashMap 中添加雙 Arraylist

[英]Adding to double Arraylist in HashMap

我正在嘗試在 java 中添加一定數量的對,我嘗試這樣做的方法之一是在我的 HashMap 中創建一個雙 ArrayList。 如果我將 1 和 2 添加到我的列表中,我將獲得 3 作為我的密鑰。 例如:

 HashMap<Integer, ArrayList<ArrayList<Integer>>> map = new HashMap<>(); ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); map.put(list.get(0) + list.get(1), new ArrayList<>(list));

Output 看起來像這樣

 Key: 3 Value: [[1,2]]

如果我要再加一對

 Key: 3 Value: [[1,2],[0,3]]

但我不斷收到“方法不適用於 HashMap<Integer,ArrayList<ArrayList>> 類型不適用於 arguments (int, new ArrayList<>(list))”

我也試過

 new ArrayList<>(new ArrayList<>(list))

認為我可能需要先初始化更大的矩陣,但遺憾的是我最終遇到了同樣的錯誤。

這一行:

new ArrayList<>(list)

創建一個平面ArrayList<Integer> ,而HashMap期待ArrayList<ArrayList<Integer>> 同樣, new ArrayList<>(new ArrayList<>(list))也會創建一個平面 Integer 列表,因為您只是做了兩次相同的事情。 請參閱 ArrayList 的ArrayList 文檔

考慮到二維列表設置,這是一種可行的方法:

HashMap<Integer, List<List<Integer>>> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
List<List<Integer>> outer = new ArrayList<>();
outer.add(list);
map.put(list.get(0) + list.get(1), outer);

您還可以創建一些可以促進這一點的 lambdas。 例如。

Map<Integer, List<List<Integer>>> map1 = new HashMap<>();

創建一個 function 來對列表的元素求和。

Function<List<Integer>, Integer> sum =
        list -> list.stream()
        .collect(Collectors.summingInt(Integer::intValue));

然后創建一個BiConsumer以獲取列表對和現有 map 並在需要時添加它們。 如果鍵為 null 或不存在,則computeIfAbsent輸入鍵的值。 返回該列表,以便可以將該對添加到新創建的列表中。

BiConsumer<List<Integer>, Map<Integer,
           List<List<Integer>>>> addToMap =
        (pair, map) -> {
            map.computeIfAbsent(sum.apply(pair),
                    v -> new ArrayList<>()).add(pair);
        };

把它們放在一起。

addToMap.accept(List.of(1,2), map1);
addToMap.accept(List.of(0,4), map1);
addToMap.accept(List.of(1,5), map1);
addToMap.accept(List.of(0,3), map1);
addToMap.accept(List.of(-1,5), map1);
addToMap.accept(List.of(-1,2,3),map1);

map1.entrySet().forEach(System.out::println);

印刷

3=[[1, 2], [0, 3]]
4=[[0, 4], [-1, 5], [-1, 2, 3]]
6=[[1, 5]]

如您所見,這不會對“對”施加任何大小限制。

對於您想要的東西,這可能有點矯枉過正,但您可能可以使用一些元素。 另請注意,上面的List.of是不可變的。

暫無
暫無

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

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