java 中如何 找出两个集合中的不重复的元素
展开全部
You can try to use Java's Set and Set's removeAll() method, for example:
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) {
Set<Integer> a = new HashSet<Integer>();
Set<Integer> b = new HashSet<Integer>();
a.add(1);
a.add(2);
b.add(2);
b.add(3);
Set<Integer> a1 = new HashSet<Integer>();
Set<Integer> b1 = new HashSet<Integer>();
a1.addAll(a);
b1.addAll(b);
System.out.println("a1 as the clone of a:"+a1);
System.out.println("b1 as the clone of b:"+b1);
a1.removeAll(b);
b1.removeAll(a);
System.out.println("In a but not in b:"+a1);
System.out.println("In b but not in a:"+b1);
}
}
Console output:
a1 as the clone of a:[1, 2]
b1 as the clone of b:[2, 3]
In a but not in b:[1]
In b but not in a:[3]
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) {
Set<Integer> a = new HashSet<Integer>();
Set<Integer> b = new HashSet<Integer>();
a.add(1);
a.add(2);
b.add(2);
b.add(3);
Set<Integer> a1 = new HashSet<Integer>();
Set<Integer> b1 = new HashSet<Integer>();
a1.addAll(a);
b1.addAll(b);
System.out.println("a1 as the clone of a:"+a1);
System.out.println("b1 as the clone of b:"+b1);
a1.removeAll(b);
b1.removeAll(a);
System.out.println("In a but not in b:"+a1);
System.out.println("In b but not in a:"+b1);
}
}
Console output:
a1 as the clone of a:[1, 2]
b1 as the clone of b:[2, 3]
In a but not in b:[1]
In b but not in a:[3]
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
for循环A,内层循环B
如果B中有元素与当前A循环相等,移除B中此元素,B循环完成,移除A中此元素,如果没有相等的,继续阁下循环
最后A,B里面剩下的就是不重复元素了
思路就是这样了
如果B中有元素与当前A循环相等,移除B中此元素,B循环完成,移除A中此元素,如果没有相等的,继续阁下循环
最后A,B里面剩下的就是不重复元素了
思路就是这样了
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询