【问题标题】:Java Element-wise merge of two list两个列表的Java元素合并
【发布时间】:2021-11-05 01:21:05
【问题描述】:

我有两个 List<Int> int 像 {1,2,3} 和 {4,5,6}。

我需要获得一个List<List<Int>>,例如: ((1,4),(2,5),(3,6))

我应该如何进行?我试过 for 但我只能得到笛卡尔积

【问题讨论】:

  • 使用传统的 for 循环(使用索引)并通过索引访问元素。或者使用 2 个迭代器并在两者上调用 next()(对于链表会更快)。
  • 请告诉我们你的尝试!
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: java list merge elementwise-operations


【解决方案1】:

这里的关键数字是 3:你想循环 3 次。每个循环,您都知道该怎么做:从 input1 中获取第 X 个数字,从 input2 中获取第 X 个数字,将它们放在一个 size-2 列表中,然后在输出中形成第 X 个条目。

int[] in1 = ...;
int[] in2 = ...;
int[][] out;

assert input1.length == input2.length;
int len = input1.length;
out = new int[len][];
for (int i = 0; i < len; i++) {
  out[i] = new int[] {input1[i], input2[i]};
}

【讨论】:

  • 谢谢。我的问题是我必须返回一个列表列表,我不知道如何操作它
  • int[][]List&lt;List&lt;Integer&gt;&gt; 之间几乎没有区别——如果我解决了这个问题,我只是给你复制和粘贴的东西,而你什么也学不到。您应该能够轻松地了解上述内容并弄清楚。
  • 是的,我知道,但我无法将列表的索引作为数组的索引,我发布了一个可行的解决方案,我认为是正确的
【解决方案2】:

好的,我解决了这样的问题:

public List<List<V>> Lister (List<V> list1, List<V> list2){
    List<List<V>> result = new ArrayList<>();
    if (list1.size() == list2.size()) {
      for(int i =0; i<list1.size(); i++){
        List<V> tempList = new ArrayList<>();
        tempList.add(list1.get(i));
        tempList.add(list2.get(i));
        result.add(tempList);
      }
    }
    return result;
  }

【讨论】:

  • 我没有得到您的问题,您已经完成了,并且假设列表具有相同的大小,您可以轻松地使用另一个循环访问它。 pastebin.com/WbHR62pD
  • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
【解决方案3】:
List<Integer> list1 = List.of(1,2,3);
List<Integer> list2 = List.of(4,5,6);
List<List<Integer>> merged = mergeLists(list1, list2);
System.out.println(merged); 

打印

[[1, 4], [2, 5], [3, 6]]

此方法接受任何类型的列表&lt;T&gt;,只要它们包含相同的类型并且长度相同。

  • 如果长度不同,则抛出异常。
  • 分配一个返回的ArrayList
  • 将索引初始化为 0
  • 使用增强的 for 循环,遍历一个列表并索引另一个列表
  • 通过List.of() 将新列表添加到返回列表。由于List.of() 是不可变的,它作为参数传递给new ArrayList&lt;&gt;()
  • 在循环结束后返回结果。
public static <T> List<List<T>> mergeLists(List<T> list1,
        List<T> list2) {
    if (list1.size() != list2.size()) {
        throw new IllegalArgumentException("Lists must be the same size");
    }
    List<List<T>> list = new ArrayList<>();
    int i = 0;
    for (T v1 : list1) {
        list.add(new ArrayList<>(List.of(v1, list2.get(i++))));
    }
    return list;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2021-06-13
    • 2022-09-30
    • 2018-11-27
    相关资源
    最近更新 更多