Skip to content

Instantly share code, notes, and snippets.

@eutkin
Created September 4, 2018 14:15
Show Gist options
  • Save eutkin/d732dd6b5d82179f0311d563b1589eeb to your computer and use it in GitHub Desktop.
Save eutkin/d732dd6b5d82179f0311d563b1589eeb to your computer and use it in GitHub Desktop.
cross join
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