本文分享的示例代码实现提取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个集合中的相同和不同元素代码示例的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
相关文章
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250