Java List removeAll() method removes all of its elements that are also present in the given list. The method throws UnsupportedOperationException if the operation is not supported by the list.

Java List removeAll()方法将删除其所有在给定列表中也存在的元素。 如果列表不支持该操作,则该方法将引发UnsupportedOperationException。

If the given collection is null, NullPointerException is thrown.

如果给定的集合为null,则抛出NullPointerException 。

This method returns true if the list is changed, otherwise false.

如果更改列表,则此方法返回true ,否则返回false

Java列表removeAll()示例 (Java List removeAll() Examples)

Let’s look at some examples of removeAll() method with different types of list implementations.

让我们看一下带有不同类型的列表实现的removeAll()方法的一些示例。

1. ArrayList removeAll()示例 (1. ArrayList removeAll() Example)

List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("C");
list.add("B");
list.add("A");
System.out.println(list);List<String> removeList = List.of("A", "B");boolean isRemoved = list.removeAll(removeList);
System.out.println(list);
System.out.println(isRemoved);

Output:

输出:

[A, B, C, C, B, A]
[C, C]
true

2. LinkedList removeAll()示例 (2. LinkedList removeAll() Example)

List<Integer> linkedList = new LinkedList<>();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
System.out.println(linkedList);
boolean flag = linkedList.removeAll(List.of(1, 2));
System.out.println(linkedList);
System.out.println(flag);

Output:

输出:

[1, 2, 3]
[3]
true

3.列出removeAll()UnsupportedOperationException (3. List removeAll() UnsupportedOperationException)

If we invoke removeAll() method on an Unmodifiable list, we will get UnsupportedOperationException.

如果我们在U​​nmodifiable列表上调用removeAll()方法,则将获得UnsupportedOperationException。

List.of() method returns an Unmodifiable list.

List.of()方法返回一个不可修改的列表。

jshell> List<Integer> list = List.of(1, 2);
list ==> [1, 2]jshell> list.removeAll(List.of(1));
|  Exception java.lang.UnsupportedOperationException
|        at ImmutableCollections.uoe (ImmutableCollections.java:72)
|        at ImmutableCollections$AbstractImmutableCollection.removeAll (ImmutableCollections.java:80)
|        at (#67:1)jshell>

Java List removeAll() UnsupportedOperationException

Java列表removeAll()UnsupportedOperationException

4.列出removeAll()NullPointerException (4. List removeAll() NullPointerException)

jshell> List<Integer> list = new ArrayList<>();
list ==> []jshell> list.removeAll(null);
|  Exception java.lang.NullPointerException
|        at Objects.requireNonNull (Objects.java:221)
|        at ArrayList.batchRemove (ArrayList.java:847)
|        at ArrayList.removeAll (ArrayList.java:822)
|        at (#71:1)jshell>

Java List removeAll() NullPointerException

Java列表removeAll()NullPointerException

5. Java列表removeAll()不起作用 (5. Java List removeAll() Not Working)

If you look at the implementation of removeAll() method in ArrayList/LinkedList, it uses following methods internally.

如果查看ArrayList / LinkedList中的removeAll()方法的实现,则它在内部使用以下方法。

removeAll() -> contains() -> indexOf() -> indexOfRange() -> equals()

So, it’s necessary that the list elements have proper implementation of equals() and hashCode() methods. Otherwise, you will get unwanted results.

因此,列表元素必须具有equals()和hashCode()方法的正确实现。 否则,您将得到不想要的结果。

Here is an example where the equals() and hashCode() method is not implemented for the List elements and the removeAll() operation is not working as expected.

这是一个示例,其中未对List元素实现equals()和hashCode()方法,并且removeAll()操作未按预期工作。

package com.journaldev.java;import java.util.ArrayList;
import java.util.List;public class ArrayListRemoveAll {public static void main(String[] args) {List<Record> list = new ArrayList<>();list.add(new Record(1, "Hi"));list.add(new Record(2, "Hello"));list.add(new Record(3, "Howdy"));System.out.println("Original List =" + list);list.removeAll(List.of(new Record(1, "Hi"), new Record(2, "Hello")));System.out.println("Updated List =" + list);}}class Record {private int id;private String data;Record(int i, String d) {this.id = i;this.data = d;}@Overridepublic String toString() {return String.format("R{%d, %s}", this.id, this.data);}
}

Output:

输出:

Original List =[R{1, Hi}, R{2, Hello}, R{3, Howdy}]
Updated List =[R{1, Hi}, R{2, Hello}, R{3, Howdy}]

It seems that the removeAll() method is not working. Now let’s add equals() and hashCode() method implementations to the Record class.

看来removeAll()方法不起作用。 现在让我们将equals()和hashCode()方法实现添加到Record类。

@Override
public int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((data == null) ? 0 : data.hashCode());result = prime * result + id;return result;
}@Override
public boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Record other = (Record) obj;if (data == null) {if (other.data != null)return false;} else if (!data.equals(other.data))return false;if (id != other.id)return false;return true;
}

Updated Output:

更新的输出:

Original List =[R{1, Hi}, R{2, Hello}, R{3, Howdy}]
Updated List =[R{3, Howdy}]

Now the removeAll() method is working as we expected. So whenever you feel that the removeAll() operation is not working as expected, check the equals() and hashCode() implementations in the list elements class.

现在removeAll()方法正在按预期工作。 因此,每当您感到removeAll()操作未按预期工作时,请检查list elements类中的equals()和hashCode()实现。

参考资料 (References)

  • List removeAll() API Doc列出removeAll()API文档
  • StackOverflow: ArrayList removeAll() Not WorkingStackOverflow:ArrayList removeAll()不起作用

翻译自: https://www.journaldev.com/31875/java-list-removeall-collection-examples

Java列表removeAll(Collection)示例相关推荐

  1. Java™ 教程(Collection接口)

    Collection接口 Collection表示一组称为其元素的对象,Collection接口用于传递需要最大通用性的对象集合,例如,按照惯例,所有通用集合实现都有一个带有Collection参数的 ...

  2. Java集合:Collection接口

    Collection是一个接口,继承自Iterable.我们先看一下Iterable接口的源码 一.Iterable package java.lang;import java.util.Iterat ...

  3. Java 9 特性与示例

    Java 9 特性与示例 Java 9是一个主要版本,它为开发人员带来了许多功能.在本文中,我们将详细介绍Java 9的功能. Java 10已发布,有关Java 10发行版的完整概述,请参阅Java ...

  4. Java列表add()和addAll()方法

    1. Java清单add() (1. Java List add()) This method is used to add elements to the list. There are two m ...

  5. day15 java基础(Collection类,List类,Object类)

    -----------------------------------day15 总结------------------------------------------------- 1:对象数组( ...

  6. Java集合系列---Collection源码解析及整体框架结构

    集合的整体框架结构及依赖关系 1.Collection public interface Collection<E> extends Iterable<E> {} Collec ...

  7. JAVA GC(Garbage Collection)及OOM那些事

    2019独角兽企业重金招聘Python工程师标准>>> JAVA运行时内存区域 程序计数器 一块很小的内存空间 当前线程所执行的字节码的行号指示器 当前线程私有 不会出现OutOfM ...

  8. html无序列表的滚动效果,html无序列表标签和有序列表标签使用示例

    原标题:html无序列表标签和有序列表标签使用示例 一.上下层列表标签: : 上层dt 下层dd:封装的内容会被自动缩进的效果 复制代码 代码如下: 运动户外 板鞋 篮球鞋 足球鞋 跑步鞋 二.定义有 ...

  9. R语言可视化绘制及PDF使用字体参数列表:查看字体列表、可视化绘制图像中的字体参数列表、字体示例并写入pdf

    R语言可视化绘制及PDF使用字体参数列表:查看字体列表.可视化绘制图像中的字体参数列表.字体示例并写入pdf 目录 R语言可视化绘制及PDF使用字体参数列表:查看字体列表.可视化绘制图像中的字体参数列 ...

最新文章

  1. R语言使用coin包应用于独立性问题的置换检验(permutation tests、响应变量是否独立于组、两个数值变量是独立的吗、两个分类变量是独立的吗)、以及coin包的常用置换检验函数
  2. 网络品牌推广浅析网站标题该如何进行SEO优化?
  3. C 判断 —— if...else 语句(bool变量、float变量、指针变量与“零值”进行比较)(else 到底与哪个 if 配对呢? if 语句后面的分号?)
  4. 【Python】PAT-1034 有理数四则运算
  5. 异常处理——上传文件到HDFS,put: `.': No such file or directory
  6. 对计算机网络与系统的认识,浅谈对计算机网络的认识
  7. python有序队列_【Python】:拓展Queue实现有序不重复队列
  8. spark基础之RDD和DataFrame的转换方式
  9. 2022年春运火车票明起开卖
  10. Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2问题解决
  11. 不要在考虑需求之前更多的在意你的职业镀金
  12. 全球及中国菖蒲根提取物行业发展规模及投资方向分析报告2022-2028年
  13. 搭建属于你的家庭网络实时监控–HTML5在嵌入式系统中的应用·高级篇
  14. python泰坦尼克号数据分析_Python实战—泰坦尼克号生还者数据分析
  15. 关于DM MPP的搭建
  16. 扎进“手机”红海,蔚来改造“生态圈”
  17. Prometheus-监控主机基础指标配置及告警
  18. Lua实现三目运算符
  19. java 解码_java编码与解码
  20. c语言 矩阵反转输出

热门文章

  1. Unity3d Material(材质) 无缝拼接
  2. (转)SSDTShadow Hook的实现,完整代码
  3. Introduction to Latent Dirichlet Allocation
  4. 数据库表多维度数据的计算和汇总
  5. [转载] pythonjson构建二维数组_python二维键值数组生成转json的例子
  6. [转载] Python之Numpy模块中的方法详解
  7. [转载] numpy教程:矩阵matrix及其运算
  8. [转载] C++学习之异常处理详解
  9. 【iOS开发】使用iFrameExtractor实现视频直播
  10. 超哥笔记 --nginx入门(6)