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

后端 未结 3 706
不知归路
不知归路 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.

    0 讨论(0)
  • 2020-12-16 00:06

    My StreamEx library has some syntactic sugar for this case:

    StreamEx.zip(names, ages, (name, age) -> name+":"+age).forEach(System.out::println)
    

    Basically inside it's the same as in accepted answer. The only difference is that IllegalArgumentException will be thrown if size of lists differs.

    0 讨论(0)
  • 2020-12-16 00:06

    While Alexis C. answer is correct, one would argue it is the easiest way to achieve requested behavior in Java 8. I propose:

    int[] i = {0};
    names.forEach(name -> {
        System.out.println(name + ages.get(i[0]++));
    });
    

    Or even without index:

    List<Integer> agesCopy = new ArrayList<Integer>(ages);
    names.forEach(name -> {
        System.out.println(name + agesCopy.remove(0));
    });
    
    0 讨论(0)
提交回复
热议问题