如何使用java从两个列表中获取不常见元素的列表



我需要在比较两个列表时获取不常见元素的列表。前任:-

List<String> readAllName = {"aaa","bbb","ccc","ddd"};
List<String> selectedName = {"bbb","ccc"};

在这里,我希望另一个列表中来自 readAllName 列表("aaa","ccc","ddd")的不常见元素。不使用 remove() 和 removeAll()。

假设预期的输出是aaa, ccc, eee, fff, xxx(所有不常见的项目),您可以使用 List#removeAll ,但您需要使用它两次才能获取名称中但不在 name2 中的项目和名称 2 中但不在名称中的项目:

List<String> list = new ArrayList<> (name);
list.removeAll(name2); //list contains items only in name
List<String> list2 = new ArrayList<> (name2);
list2.removeAll(name); //list2 contains items only in name2
list2.addAll(list); //list2 now contains all the not-common items

根据您的编辑,您不能使用removeremoveAll - 在这种情况下,您可以简单地运行两个循环:

List<String> uncommon = new ArrayList<> ();
for (String s : name) {
    if (!name2.contains(s)) uncommon.add(s);
}
for (String s : name2) {
    if (!name.contains(s)) uncommon.add(s);
}

您可以使用番石榴库来执行此操作。Sets 类具有差异方法

我认为你必须运行它两次才能从双方获得所有差异。

最新更新