Home > Mobile >  Check if two lists (one is nested) are mutually exclusive
Check if two lists (one is nested) are mutually exclusive

Time:11-17

I want to compare two list (one is nested) for mutual exclusivity. Problem is that this code is printing false even if they have only one element in common. I need it to print false if they have both elements in common.

output I'm getting: false true false

Desired output: true true false

...
ArrayList<String> properties = new ArrayList<>(Arrays.asList("A", "B"));
ArrayList<ArrayList<String> > pairs = new ArrayList<ArrayList<String> >();

pairs.add(new ArrayList<>(Arrays.asList("A", "C")));
pairs.add(new ArrayList<>(Arrays.asList("D", "C")));
pairs.add(new ArrayList<>(Arrays.asList("A", "B")));

for(int i = 0; i< pairs.size(); i  ) {
    System.out.println(Collections.disjoint(properties, pairs.get(i)));
} 

CodePudding user response:

So, as I understand your question now after your edit, you are making it too difficult. There is no need for Collections.disjoint() here, if you are only looking for non-equal lists. If you want to print false if you come across a List with identical contents, why not simply use equals()?

So the check becomes

for (int i = 0; i < pairs.size(); i  ) {
   System.out.println(!properties.equals(pairs.get(i)));
}

printing the following output

true
true
false
  • Related