2

I have two list like

List<String> list1 = Arrays.asList("A","B");
List<String> list2 = Arrays.asList("C","D");

I want to iterate both lists at the same time in java 8 and my output should be

A C
B D

Tatkal
  • 478
  • 4
  • 7
  • 25
  • You can find a lot of good answers here https://stackoverflow.com/questions/189559/how-do-i-join-two-lists-in-java – Tuan Hoang Sep 30 '20 at 06:07

2 Answers2

0

You can create an IntStream to generate indices and then map each index to the String.

   IntStream.range(0, Math.min(list1.size(), list2.size()))
             .mapToObj(i -> list1.get(i)+" "+list2.get(i))
             .forEach(System.out::println);
Umesh Sanwal
  • 449
  • 3
  • 10
0

You don't need Stream API as long as two Iterators can do all you need:

Iterator<String> iterator1 = list1.iterator();
Iterator<String> iterator2 = list2.iterator();

while (iterator1.hasNext() && iterator2.hasNext()) {
    System.out.println(iterator1.next() + " " + iterator2.next());   // or add to a list
}
Nikolas Charalambidis
  • 29,749
  • 7
  • 67
  • 124