本文分享的示例代碼實現提取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個集合中的相同和不同元素代碼示例的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!