gpt4 book ai didi

java - 如何只从列表中删除一个重复项?

转载 作者:行者123 更新时间:2023-11-29 18:46:44 25 4
gpt4 key购买 nike

我有一个列表:(x, y, y,z)

我有另一个列表:(x, y)

您想从第一个列表中删除也属于第二个列表的项目。

例如:我希望结果为 (y,z)

我该怎么做?

编辑: 如果我使用 removeAll。示例列表返回 (z)

最佳答案

这个解决方案似乎可以接受。

List<String> one = new ArrayList<>();
one.add("x");
one.add("y");
one.add("y");
one.add("z");
List<String> two = new ArrayList<>();
two.add("x");
two.add("y");

for (String s : two)
{
one.remove(s);
}

System.out.println("one : " + one);

输出:

one : [y, z]


List.remove(Object o)文档:

Removes the first occurrence of the specified element from this list, if it is present (optional operation). If this list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).


注意:算法复杂度为O(n*m),避免使用 2 个非常大的列表(其中 nm 是列表大小)。

关于java - 如何只从列表中删除一个重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51582013/

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