Created
September 4, 2018 14:15
-
-
Save eutkin/d732dd6b5d82179f0311d563b1589eeb to your computer and use it in GitHub Desktop.
cross join
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
import java.util.ArrayList; | |
import java.util.Collection; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
import static java.util.Arrays.asList; | |
/** | |
* @author eutkin | |
*/ | |
public class CrossJoiner { | |
@SafeVarargs | |
public static List<List<Object>> crossJoin(Collection<Object>... nullableCollections) { | |
if (nullableCollections == null || nullableCollections.length == 0) { | |
return Collections.emptyList(); | |
} | |
List<Collection<Object>> collections = Stream | |
.of(nullableCollections) | |
.filter(collection -> collection != null && !collection.isEmpty()) | |
.collect(Collectors.toList()); | |
List<List<Object>> left = collections.get(0).stream().map(elem -> { | |
List<Object> buffer = new ArrayList<>(); | |
buffer.add(elem); | |
return buffer; | |
}).collect(Collectors.toList()); | |
for (int i = 1; i < collections.size(); i++) { | |
final int current = i; | |
left = left.stream().flatMap(l -> collections.get(current).stream().map(r -> { | |
List<Object> buffer = new ArrayList<>(); | |
buffer.addAll(l); | |
buffer.add(r); | |
return buffer; | |
})).collect(Collectors.toList()); | |
} | |
return left; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment