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

后端 未结 3 729
不知归路
不知归路 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-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 agesCopy = new ArrayList(ages);
    names.forEach(name -> {
        System.out.println(name + agesCopy.remove(0));
    });
    

提交回复
热议问题