Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Every combination of 2 strings in List Java 8 [duplicate]

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

like image 686
Lau Avatar asked Dec 14 '22 00:12

Lau


1 Answers

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.

like image 60
4castle Avatar answered Feb 04 '23 00:02

4castle