Java - 在两个列表之间获得差异

时间:2018-01-13 01:13:18

标签: java

我试图在Java中找到两个列表之间的区别。我正在使用这个示例(returning difference between two lists in java)建议使用removeAll()来查找差异,但这不起作用。相反,我似乎得到了coachesteachers的组合列表。

代码:

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);
}

输出:

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

如何检查teachers是否缺少值Tyler,以便返回Tyler

1 个答案:

答案 0 :(得分:1)

例如,在不丢失教练名单的情况下,看看谁只是一名教练而不是教师:

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);
}