gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:35:38 24 4
gpt4 key购买 nike

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

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 ,但是您需要使用它两次才能获取 name 中但不在 name2 中的项目以及 name2 中但不在 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
<小时/>

根据您的编辑,您不能使用 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);
}

关于java - 如何使用java从两个列表中获取不常见元素的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14645319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com