Home Java - Getting Difference Between Two Lists
Reply: 1

Java - Getting Difference Between Two Lists

Jon
1#
Jon Published in 2018-01-13 01:13:17Z

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?

DigitalNinja
2#
DigitalNinja Reply to 2018-01-13 01:39:04Z

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);
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.352576 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO