I need to get the list of uncommon element while comparing two lists . ex:-
List<String> readAllName = {"aaa","bbb","ccc","ddd"};
List<String> selectedName = {"bbb","ccc"};
here i want uncommon elements from readAllName list ("aaa","ccc","ddd") in another list. Without Using remove()and removeAll().
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.