Creating a stream of multiple tuples out of one tuple pair

Let’s say I have a tuple (1, 2). I want to create a stream, that gives me all possible combinations of that tuples’ values. So I want to create a stream that looks like this:

[(1, 1), (1, 2), (2, 1), (2, 2)]

This is my class for my tupels:

public class Tupel<T> {

    private final T first;
    private final T second;

    public Tupel(T first, T second) {
        assert first != null;
        assert second != null;

        this.first = first;
        this.second = second;

    public T getFirst() {
        return first;

    public T getSecond() {
        return second;



This is my class for my tuple pairs:

public class TupelPairs<T> {
    private TupleSet<T> tupleSet;

    public TupelPais(TupleSet<T> tupleSet) {
    this.tupelSet = tupleSet;
    //This is where I want to create my tuple pairs

    public Stream<Tupel<T>> getElements() {
    return; //This is where I want to return my Stream of those tupel pairs

How could do I create those tuple pairs?


First you need to produce every pair from your set and easiest way I can think of right now

List<T> vals = new ArrayList(tupleSet);
Set<Tuple<T>> set = new HashSet();

for(int i = 0; i < vals.size() - 1; i++) {
  for (int j = i+1; j < vals.size(); j++) {
     set.add(new Tuple(vals.get(i), vals.get(j)));

Now for each tuple we need to generate permutations of its elements, since you have two elements in tuple only so there would be 4 permutations always.

You can find the algorithm to generate permutations online, you can store each permutation combination in tuple, so your one tuple generated above in for loop will generate 4 tuples

[(0,1), (1,2)] //we created this in for loop

This will produce using algorithm like this


Now having this list, you can easily stream it using stream API function provided for every collection.

Leave a Reply

Your email address will not be published. Required fields are marked *