如何通过包含相同索引的值将两个列表合并为一个列表。
我有 2 个列表,我想通过包含相同索引的值合并两个列表。
(如果可能的话,请给我推荐java 8: Streams的方法。)
List<String> a = Arrays.asList("1", "2", "3");
List<String> b = Arrays.asList("10", "20", "30");
输出:
{"11", "22", "33"}
最佳答案
仅使用标准库的解决方案:
List<String> a = Arrays.asList("1", "2", "3");
List<String> b = Arrays.asList("10", "20", "30");
List<String> c = IntStream.range(0, a.size())
.map(i -> Integer.parseInt(a.get(i)) + Integer.parseInt(b.get(i)))
.mapToObj(Integer::toString)
.collect(Collectors.toList());
请注意,输入列表将数字存储为 String
,如示例中指定的那样。另外,您可以将 map()
和 mapToObj()
调用合并为一个 mapToObj()
调用,但为了清楚起见,我想将其分开.
它还假设两个列表的大小相同,如果不同,将抛出ArrayIndexOutOfBoundsException
。
关于java - 将两个 List<Integer> 的每个元素求和到一个新列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52932902/