How to get the list of uncommon element from two list using java?

北城以北 提交于 2019-12-01 15:01:20

Assuming the expected output is aaa, ccc, eee, fff, xxx (all the not-common items), you can use List#removeAll, but you need to use it twice to get both the items in name but not in name2 AND the items in name2 and not in name:

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

As per your edit, you can't use remove or removeAll - in that case you can simply run two loops:

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

You can use the Guava libraries to do this. The Sets class has a difference method

You would have to run it twice I think to get all the differences from both sides.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!