添加到 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));

输出看起来像这样

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

如果我再添加一对

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

但我一直收到 'method is not applicable in the type HashMap<Integer,ArrayList<ArrayList>> is not applicable for the arguments (int, new ArrayList<>(list))'

我也试过了

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

我想我可能需要先初始化更大的矩阵,但遗憾的是我最终遇到了同样的错误。

这一行:

new ArrayList<>(list)

创造了一个平面 ArrayList<Integer>,而 HashMap 期待 ArrayList<ArrayList<Integer>>。出于同样的原因,new ArrayList<>(new ArrayList<>(list)) 也创建了一个平面整数列表,因为您只是在做同样的事情两次。请参阅 API document 以获得 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);

您还可以创建一些 lambda 表达式来促进这一点。例如。

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

创建一个函数来对列表的元素求和。

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

然后创建一个 BiConsumer 以获取列表对和现有地图,并在需要时添加它们。 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 是不可变的。