如何使用 Stream API java 8 一起打印两个列表? [英] How to print two lists together using Stream API java 8?

查看:23
本文介绍了如何使用 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 一起打印两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆