Search code examples
listjava-8nested-loops

Cross join two lists java


I have a class ABC which contains two integer fields

public class ABC{
  private Integer x;
  private Integer y;

   // getters and setters
}

I have two lists : xValues and yValues, which contain list of integers of x and y values respectively.

List<Integer> xValues = fetchAllXValues();  //say list xValues contains {1,2,3}
List<Integer> yValues = fetchAllYValues();  //say list yValues contains {7,8,9}

Now what I want is to create an ABC object using each values of xValues list with each values of yValues list. I dont want to use nested for loop. What would be a more efficient way to solve this?

sample output objects for ABC are:

     ABC(1,7);
     ABC(1,8);
     ABC(1,9);
     ABC(2,7);
     ABC(2,8);
     ABC(2,9);
     ABC(3,7);
     ABC(3,8);
     ABC(3,9);

Solution

  • Iterate over the first list and on every iteration iterate over the second list:

    xValues.stream()
        .flatMap(x -> yValues.stream().map(y -> new ABC(x, y)))
        .collect(toList());