如何通过包含相同索引的值将两个列表合并为一个列表。
我有2个列表,我想按包含相同索引的值合并两个列表。
(如果可能,请以Java 8:Streams的方式建议我。)
List<String> a = Arrays.asList("1", "2", "3");
List<String> b = Arrays.asList("10", "20", "30");
输出:
{"11", "22", "33"}
答案 0 :(得分:3)
仅使用标准库的解决方案:
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
。
答案 1 :(得分:2)
您尝试使用zip吗? {{3}}有一个不错的图书馆
StreamUtils.zip(a.stream(), b.stream(), (e1,e2) -> (Integer.parseInt(e1) + Integer.parseInt(e2)).toString())
答案 2 :(得分:1)
如果您使用Eclipse Collections,则可以使用zip
:
List<String> a = Arrays.asList("1", "2", "3");
List<String> b = Arrays.asList("10", "20", "30");
List<String> c = Lists.adapt(a).zip(b)
.collectInt(p -> Integer.parseInt(p.getOne()) +Integer.parseInt(p.getTwo()))
.collect(Integer::toString);
System.out.println(c);
输出:[11, 22, 33]
您还可以将Eclipse Collections中的Collectors2
与Stream
一起使用。
List<String> a = Arrays.asList("1", "2", "3");
List<String> b = Arrays.asList("10", "20", "30");
List<String> c = a.stream().collect(Collectors2.zip(b))
.collectInt(p -> Integer.parseInt(p.getOne()) + Integer.parseInt(p.getTwo()))
.collect(Integer::toString);
System.out.println(c);
输出:[11, 22, 33]
注意:我是Eclipse Collections的提交者。