Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print two lists together using Stream API java 8?

I have two lists as follow

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));
}

Is there a way to do it using Stream API java 8?

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

names.stream().forEach(System.out::println);
like image 973
MChaker Avatar asked May 09 '15 20:05

MChaker


1 Answers

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);

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.

like image 87
Alexis C. Avatar answered Oct 10 '22 15:10

Alexis C.