javajava-streamcartesian-product

How to combine two lists using the Java stream API


Given the following lists of strings:

partnersName = ["partner1","partner2"];

totalDates = ["2022-05-18","2022-05-19"];

Here is the following code which gives output that I want:

for (int i = 0; i < partnersName.size(); i++) {
    if (totalDates.isEmpty()) {
        totalDates.add(partnersName.get(i));
    } else {
        for (int j = 0; j < totalDates.size(); j++) {
            totalDates.set(j, partnersName.get(i) +"/" +totalDates.get(j));
        }
    }
}

Desired output:

output = ["partner1/2022-05-18","partner2/2022-05-18","partner1/2022-05-19","partner2/2022-05-19"];

I want to reduce the line of code using the Java stream API. Could anyone help to get stream API code?


Solution

  • Here is one way.

    List<String> partnerName = List.of("partner1","partner2");
    List<String> totalDates = List.of("2022-05-18","2022-05-19");
    
    List<String> result = partnerName.stream()
            .flatMap(name -> totalDates.stream()
                    .map(date->String.join("/", name, date)))
            .toList();
        
    System.out.println(result);
    

    prints

    [partner1/2022-05-18, partner1/2022-05-19, partner2/2022-05-18, partner2/2022-05
    -19]