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

标签 java android list arraylist

我有一个列表:(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/

相关文章:

java - 多种类型的过滤器<Object>

Java 堆空间 : Applets

java - 在 Solr DataImportHandler 中从 Oracle 日期获取正确的时间

Android Kotlin - 捕获异常仍然使程序崩溃

Android - 如何使用 url 从实时音频流/互联网广播 channel 获取元数据

list - 如何使用 theme_item_list() 在 drupal7 中实现多级列表?

html - 堆栈显示 :block, 但保留内部文本的宽度 - 这可能吗?

java - 可重用的 Java StringReader

java - Netty不会写

Java SSL 握手失败有时会失败,具体取决于 VM 参数/属性