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

查看:308
本文介绍了如何使用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天全站免登陆