0

for simplicity I have 2 lists of String and I need to join the strings into one and create another list. For eg --

List 1 = [a,b,c,d]
List 2 = [e,f,g,h]

I want the output as

List3 = [ae,bf,cg,dh]

I can do this using regular for loops. but dont know how to proceed for java8

I am trying to get myself thinking in n Java 8 :-)

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Roma
  • 333
  • 3
  • 11

1 Answers1

3

I'm not sure there's a better (easy) way to do this than to access the elements from the two lists by index:

List<String> zipped = IntStream.range(0, list.size())
    .mapToObj(i -> list1.get(i) + list2.get(i))
    .collect(Collectors.toList());
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • can I add another list after zipping the first two lists into one before collecting into a list? – Roma Sep 30 '17 at 05:22
  • 1
    You haven't mentioned in this code, what `list` is. Also, this will throw `java.lang.IndexOutOfBoundsException` if `list.size()` is greater than the size of `list1` or that of `list2`. – Arvind Kumar Avinash Feb 09 '21 at 10:42