之前遇到一个长得很有趣的面试官问两个集合怎么求他们的交集、并集、茶集
,回答之后觉得非常有意思,在这里记录一下:
集合A:{阿福,张飞,李白,鲁班}
集合B:{诸葛亮,李白,马超}
交集:{李白}
public class CollectionTest {
public static void main(String[] args) {
List<String> collectionA = new ArrayList<>();
List<String> collectionB = new ArrayList<>();
Collections.addAll(collectionA, "阿福", "张飞", "李白", "鲁班");
Collections.addAll(collectionB, "诸葛亮", "李白", "马超");
//求交集
collectionA.retainAll(collectionB);
collectionA.forEach(System.out::println);
}
}
collectionA.retainAll(collectionB);
Collection.retainAll()方法方法是在指定集合A中,通过迭代器遍历集合A的元素,只留下包含集合B的元素,其他元素都删除。
集合A:{阿福,张飞,李白,鲁班}
集合B:{诸葛亮,李白,马超}
交集:{阿福,张飞,李白,鲁班,诸葛亮,李白,马超}
public class CollectionTest {
public static void main(String[] args) {
List<String> collectionA = new ArrayList<>();
List<String> collectionB = new ArrayList<>();
Collections.addAll(collectionA, "阿福", "张飞", "李白", "鲁班");
Collections.addAll(collectionB, "诸葛亮", "李白", "马超");
//求并集
collectionA.addAll(collectionB);
collectionA.forEach(System.out::println);
}
}
集合A:{阿福,张飞,李白,鲁班}
集合B:{诸葛亮,李白,马超}
差集:{阿福,张飞,鲁班,诸葛亮,马超}
public class CollectionTest {
public static void main(String[] args) {
List<String> collectionA = new ArrayList<>();
List<String> collectionB = new ArrayList<>();
Collections.addAll(collectionA, "阿福", "张飞", "李白", "鲁班");
Collections.addAll(collectionB, "诸葛亮", "李白", "马超");
//求差集
List<String> copyCollectionA = new ArrayList<>(collectionA);
collectionA.removeAll(collectionB);
collectionB.removeAll(copyCollectionA);
collectionA.addAll(collectionB);
collectionA.forEach(System.out::println);
}
}