Search code examples
javastringlistjava-streamstringbuilder

How to connect words from two lists in Java


I want to create a sentence from words from two different lists. Like the example above:

"list1w1 list2w1 list1w2 list2w2 list1w3 list2w3..."

I know how to do it with for loop, but I want to use streams. Is it even possible?

My current solution:

StringBuilder result = new StringBuilder();
for(int i=0; i<doses.size(); i++)
result.append(String.format("%s %s<br>", list1.get(i), list2.get(i)));

Solution

  • Use an IntStream:

    String res = IntStream.range(0, list1.size())
            .mapToObj(i -> String.format("%s %s", list1.get(i), list2.get(i)))
            .collect(Collectors.joining("<br>"));