-6

I am trying to find the difference between two lists in Java. I am using this example (returning difference between two lists in java) that suggests to use removeAll() to find the difference but that is not working. Instead, I seem to be getting a combined list of coaches and teachers.

Code:

List<String> coaches = new ArrayList<>();
coaches.add("Josh");
coaches.add("Jake");
coaches.add("Tyler");

List<String> teachers = new ArrayList<>();
coaches.add("Josh");
coaches.add("Jake");

coaches.removeAll(teachers);

for (String name : coaches) {
    System.out.println("Name is: " + name);
}

Output:

Name is: Josh
Name is: Jake
Name is: Tyler
Name is: Josh
Name is: Jake

How would I check that teachers is missing the value Tyler so Tyler would be returned?

Jon
  • 8,205
  • 25
  • 87
  • 146
  • *"... but that is not working"* - How is it not working? Show us an MCVE. – Stephen C Jan 13 '18 at 01:17
  • Doing this `coaches.removeAll(teachers);` will leave you with "Tyler" in your example, letting you know that `teachers` did not contain "Tyler"... – DigitalNinja Jan 13 '18 at 01:20
  • I have updated my question to show what I am seeing – Jon Jan 13 '18 at 01:24
  • 4
    You did `coaches.add` twice instead of `teachers.add`... – DigitalNinja Jan 13 '18 at 01:24
  • I really simplified my example above. Would removeAll() also work against a List of Classes? (I didn't think a list of Strings and Classes will cause a difference) – Jon Jan 13 '18 at 01:31
  • @Jon it doesn't matter if you're using `String` or some other class: if you're calling `coaches.removeAll(teachers)` when the `teachers` is empty, nothing is going to happen to `coaches`. – Andy Turner Jan 13 '18 at 01:36

1 Answers1

3

For example, to see who is just a coach and not also a teacher without losing your list of coaches:

List<String> coaches = new ArrayList<>();
coaches.add("Josh");
coaches.add("Jake");
coaches.add("Tyler");

List<String> teachers = new ArrayList<>();
teachers.add("Josh");
teachers.add("Jake");

List<String> CoachesNotAlsoTeachers = new ArrayList<>();
CoachesNotAlsoTeachers.add(coaches);
CoachesNotAlsoTeachers.removeAll(teachers);

for (String name : CoachesNotAlsoTeachers ) {
    System.out.println("Name is: " + name);
}
DigitalNinja
  • 1,078
  • 9
  • 17
  • Thank you for pointing out my mistake in my example. I actually simplified my example too much I think. In my working issue I am using a List of Objects instead of a List of Strings. Should `removeAll()` still behave the same? – Jon Jan 13 '18 at 01:34
  • Yes, as long as they are the same kind of objects. – DigitalNinja Jan 13 '18 at 01:36