软件编程
位置:首页>> 软件编程>> java编程>> Java提取2个集合中的相同和不同元素代码示例

Java提取2个集合中的相同和不同元素代码示例

作者:weixin_38824230  发布时间:2023-11-28 05:48:41 

标签:java,集合,元素

本文分享的示例代码实现提取2个集合中相同和不同的元素

此处需要使用Collection集合所提供的一个方法:removeAll(Cellection list),removeAll方法用于从列表中移除指定collection中包含的所有元素。

语法 removeAll(Collection<?> c)

c:包含从列表中移除元素的collection对象。

该方法返回值为boolean对象,如果List集合对象由于调用removeAll方法而发生更改,则返回true,否则返回false。实现代码如下:


import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Test {
public static void main(String args[]){
//集合一
List _first=new ArrayList();
_first.add("jim");
_first.add("tom");
_first.add("jack");
//集合二
List _second=new ArrayList();
_second.add("jack");
_second.add("happy");
_second.add("sun");
_second.add("good");
Collection exists=new ArrayList(_second);
Collection notexists=new ArrayList(_second);
exists.removeAll(_first);
System.out.println("_second中不存在于_set中的:"+exists);
notexists.removeAll(exists);
System.out.println("_second中存在于_set中的:"+notexists);
}
}

运行结果:

_second中不存在于_set中的:[happy, sun, good]
_second中存在于_set中的:[jack]

来源:https://www.2cto.com/kf/201711/694758.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com