6

I would like to combine every two strings in the list and return the list of combination using java8 streams:

List<String> list;
Stream.concat(list.stream(), list.stream())
                    .collect(toList());

However this code doesn't produce combinations but just elements of the lists. What am I doing wrong. I would also like this code to be parallelized so it can run on multiple cores

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Lau
  • 3,260
  • 5
  • 16
  • 25

1 Answers1

15

Use flatMap to combine the strings in a combinatoric manner. Each string will be concatenated with each string in the list.

List<String> combinations =
    list.stream()
        .flatMap(str1 -> list.stream().map(str2 -> str1 + str2))
        .collect(toList());

Ideone Demo

To make the operations parallel, swap out .stream() for .parallelStream(). Depending on your input size, this may make the operation slower or faster.

4castle
  • 32,613
  • 11
  • 69
  • 106