Home > OS >  How do make cartesian product of two array in java
How do make cartesian product of two array in java

Time:09-27

I have two list Employee and Events from these two i want to have combination of all elements here is what i tried so far

    String sentance = "Employee [eName] playing [game] ";
    Map<String,List<String>> eventMap=new HashMap<String,List<String>>();
    List<String> empList=List.of("Ramesh","Suresh");
    eventMap.put("[eName]",  empList);
    List<String> games=List.of("Cricket","Football");
    eventMap.put("[game]", games);
    List<String> scores=List.of("56","2");
    eventMap.put("[score]", scores);
    StringBuilder builder = new StringBuilder();
    List<String> keyList = List.copyOf(eventMap.keySet());
    Matcher matcher=Pattern.compile("\\[.*?\\]").matcher(sentance);
    for (int i = 0; i < empList.size(); i  ) {
        for (int j = 0; j < games.size(); j  ) {
              int k=0;
              while(matcher.find()) { 
                     String field=matcher.group();
                     builder.append(sentance.substring(k, matcher.start()));
                     builder.append(keyList.get(0).equals(field)?empList.get(i):games.get(j));
                     k = matcher.end();
              }
        }
    }
    System.out.println(builder.toString());
}

These are the four outcomes i would like to have , but no luck so far

  1. Employee Ramesh playing Cricket with score 56
  2. Employee Ramesh playing Football with score 2
  3. Employee Suresh playing Cricket with score 56
  4. Employee Suresh playing Football with score 2

CodePudding user response:

You can use Stream API like that o(n2):

List<String> cartesianList = empList.stream()
        .flatMap(
                emp -> games.stream()
                        .map(game -> String.format("Employee %s playing %s", emp, game))
        ).collect(Collectors.toList());

System.out.println(cartesianList);

Output:

[Employee Ramesh playing Cricket, Employee Ramesh playing Football, Employee Suresh playing Cricket, Employee Suresh playing Football]

Additional, for cartesian string from 3 lists o(n3):

final List<String> cartesianList = empList.stream()
        .flatMap(
                emp -> games.stream()
                        .flatMap(game -> scores.stream()
                                .map(score -> String.format("Employee %s playing %s with score %s", emp, game, score)))
        ).collect(Collectors.toList());

Output:

[Employee Ramesh playing Cricket with score 56, Employee Ramesh playing Cricket with score 2, Employee Ramesh playing Football with score 56, Employee Ramesh playing Football with score 2, Employee Suresh playing Cricket with score 56, Employee Suresh playing Cricket with score 2, Employee Suresh playing Football with score 56, Employee Suresh playing Football with score 2]
  • Related