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
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
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);
You don't need Stream API as long as two Iterator
s 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
}