Search code examples
javacomparisontreemap

compare TreeMap key and value in Java


I have two TreeMap Like this: treemapOne:

{AUF_1413716534902_74=[Aufgabe, Function 1],
AUF_1413755000138_37=[Aufgabe, Function 2], 
AUF_1414931037395_41=[Aufgabe, Function 5],
AUF_1415377008757_59=[Aufgabe, Function 4], 
AUF_1415782696600_1801=[Aufgabe, Function 3_Eltern], 
AUF_1424125084448_1869=[Aufgabe, FunctionAlone]}

and treemaptwo:

 {AUF_1415377008757_59=[AUF_1414931037395_41], 
AUF_1415782696600_1801=[AUF_1413755000138_37, AUF_1413716534902_74]}

i want to get key(s) from treemapone which are not in elements (key or value) of treemaptwo, which means here AUF_1424125084448_1869. How can I do that?


Solution

  • Assuming both maps are instances of Map<String, List<String>>, you can do:

    // init result set with keys from treemapOne
    Set<String> remainingKeys = new HashSet<>(treemapOne.keySet());
    // remove keys in treemapTwo
    remainingKeys.removeAll(treemapTwo.keySet());
    // remove values in treemapTwo
    for (List<String> values : treemapTwo.valueSet()) {
        remainingKeys.removeAll(values);
    }