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

后端 未结 3 726
不知归路
不知归路 2020-12-15 23:06

I have two lists as follow

List names = Arrays.asList(\"James\",\"John\",\"Fred\");
List ages = Arrays.asList(25,35,15);
         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-15 23:57

    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.

提交回复
热议问题