user2511874
user2511874

Reputation:

Java 8 stream's forEach with multiple arrays

Please help me to utilize the new Java 8 features.

I have three arrays:

String[] firstnames = {"Aaa", "Bbb", "Ccc"};
String[] lastnames = {"Zzz", "Yyy", "Xxx"};
String[] mailaddresses = {"[email protected]", "[email protected]", "[email protected]"};

And want to use the new stream API to format the values into following string:

"firstname: %s\nlastname: %s\nmailaddress: %s\n"

Upvotes: 0

Views: 1075

Answers (1)

William F. Jameson
William F. Jameson

Reputation: 1853

An indirect approach with a stream of array indices is probably your best bet, given that there is no "zip" operation in the Streams API:

import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;

...

range(0, firstnames.length)
  .mapToObj(i-> String.format("firstname: %s\nlastname: %s\nmailaddress: %s\n",
      firstnames[i], lastnames[i], mailaddresses[i]))
  .collect(toList())
  .forEach(System.out::print);

Upvotes: 2

Related Questions