How to print two lists together using Stream API java 8?(如何使用 Stream API java 8 一起打印两个列表?)
问题描述
我有两个列表如下
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.
这篇关于如何使用 Stream API java 8 一起打印两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Stream API java 8 一起打印两个列表?


- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01