Home > OS >  Cartesian product in java with two lists of hashmaps<String,String>
Cartesian product in java with two lists of hashmaps<String,String>

Time:11-26

I'm trying to construct a cartesian product in java stored in d3 from d1 and d2, I'm getting an error that my can't be used on two hashmap entrys. I want to join every entry in d1 with every entry in d2.

public static List<Map<String, String>> cartesianProduct(List<Map<String, String>> d1, List<Map<String, String>> d2) {
    List<Map<String, String>> d3 = new ArrayList<>();

    int s1 = d1.size();
    int s2 = d2.size();

    for (int i = 0; i < s1; i  ) {
        for (int j = 0; j < s2; j  ) {
            d3.add(d1.get(i)   d2.get(j));
        }
    }

    return d3;
}

I've came this far, but I'm not able to join the content of the hashmaps together. Here I get the cartesian product but not joint in the same entry.

public static List<Map<String, String>> cartesianProduct(List<Map<String, String>> d1, List<Map<String, String>> d2) {
    List<Map<String, String>> result = new ArrayList<>();

    int s1 = d1.size();
    int s2 = d2.size();

    for (int i = 0; i < s1; i  ) {
        for (int j = 0; j < s2; j  ) {
            d3.add(d1.get(i));
            d3.add(d2.get(j));
        }
    }

    return d3;
}

Example:

d1 = [{Year = 1976, PersonID = 1},
{Year = 1987, PersonID = 3},
{Year = 1974, PersonID = 2}]

d2 = [{PersonID = 0,houseID = H-101},
{PersonID = 1, houseID = H-202}]

d3 = [{Year = 1976, PersonID = 1,PersonID = 0,houseID = H-101},
{Year = 1976, PersonID = 1,PersonID = 1, houseID = H-202},
{Year = 1987, PersonID = 3,PersonID = 0,houseID = H-101},
{Year = 1987, PersonID = 3,PersonID = 1, houseID = H-202},
{Year = 1974, PersonID = 2,PersonID = 0,houseID = H-101},
{Year = 1974, PersonID = 2,PersonID = 1, houseID = H-202}]

Basically I need to join the values of the d1 and d2 together into one entry, how can this be done?

CodePudding user response:

You may use Map.putAll, to merge 2 maps into one

public static List<Map<String, String>> cartesianProduct(List<Map<String, String>> d1, 
                                                         List<Map<String, String>> d2) {
    List<Map<String, String>> d3 = new ArrayList<>();

    for (int i = 0; i < d1.size(); i  ) {
        for (int j = 0; j < d2.size(); j  ) {
            map3 = new HashMap<>();
            map3.putAll(d1.get(i));
            map3.putAll(d2.get(j));
            d3.add(map3);
        }
    }    
    return d3;
}

Could be nicer with foreach loops

for (Map<String, String> i : d1) {
    for (Map<String, String> j : d2) {
        map3 = new HashMap<>();
        map3.putAll(d1);
        map3.putAll(d2);
        d3.add(map3);
    }
}
  • Related