如何使用 Stream API java 8 一起打印两个列表?

2022-01-22 00:00:00 java-8 java java-stream

我有两个列表如下

List<String> names = Arrays.asList("James","John","Fred");
List<Integer> ages = Arrays.asList(25,35,15);

我想做的是像这样打印这两个列表

What i want to do is to print those two lists like so

James:25
John:35
Fred:15

用经典的方法很容易做到

It is easy to do it using the classic way

for(int i=0;i<names.size();i++){
    System.out.println(names.get(i)+":"+ages.get(i));
}

有没有办法使用 Stream API java 8 来做到这一点?

我能做的是只打印一个列表

What i am able to do is to print only one single list

names.stream().forEach(System.out::println);

推荐答案

最简单的方法是创建一个IntStream来生成索引,然后将每个索引映射到String你想创建.

The easiest way is to create an IntStream to generate the indices, and then map each index to the String you want to create.

IntStream.range(0, Math.min(names.size(), ages.size()))
         .mapToObj(i -> names.get(i)+":"+ages.get(i))
         .forEach(System.out::println);

您也可能对这个 SO 问题感兴趣 使用 JDK8 和 lambda (java.util.stream.Streams.zip) 压缩流,因为这是您要求的功能.

Also you might be interested in this SO question Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip), because this is the kind of functionality you're asking for.

相关文章