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

时间:2019-04-10
本文章向大家介绍Java提取2个集合中的相同和不同元素代码示例,主要包括Java提取2个集合中的相同和不同元素代码示例使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文分享的示例代码实现提取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]

总结

以上就是本文关于Java提取2个集合中的相同和不同元素代码示例的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!