在 Java 編程中,經(jīng)常需要對(duì)集合進(jìn)行一些操作,比如取兩個(gè)集合的交集、并集和差集。本文將介紹如何使用 Java 集合框架中的方法來(lái)實(shí)現(xiàn)這些集合操作,并通過(guò)源碼解析來(lái)深入了解其實(shí)現(xiàn)原理。
先上代碼
import lombok.extern.slf4j.Slf4j;
import java.util.*;
@Slf4j
public class Test
{
public static void main(String[] args) {
System.out.println("===============Set=================");
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6));
// 交集
Set<Integer> intersectionSet = new HashSet<>(set1);
intersectionSet.retainAll(set2);
System.out.println("交集:" + intersectionSet);
// 并集
Set<Integer> unionSet = new HashSet<>(set1);
unionSet.addAll(set2);
System.out.println("并集:" + unionSet);
// 差集
Set<Integer> differenceSet = new HashSet<>(set1);
differenceSet.removeAll(set2);
System.out.println("差集:" + differenceSet);
System.out.println("===============List=================");
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
List<Integer> list2= new ArrayList<>(Arrays.asList(3, 4, 5, 6));
// 交集
List<Integer> intersectionList = new ArrayList<>(list1);
intersectionList.retainAll(list2);
System.out.println("交集:" + intersectionSet);
// 并集
List<Integer> unionList = new ArrayList<>(list1);
unionList.addAll(list2);
System.out.println("并集:" + unionList);
// 差集
List<Integer> differenceList = new ArrayList<>(list1);
differenceList.removeAll(list2);
System.out.println("差集:" + differenceList);
}
}
執(zhí)行結(jié)果
===============Set=================
交集:[3, 4]
并集:[1, 2, 3, 4, 5, 6]
差集:[1, 2]
===============List=================
交集:[3, 4]
并集:[1, 2, 3, 4, 3, 4, 5, 6]
差集:[1, 2]
此處各操作會(huì)改動(dòng)原始集合,所以此處的操作都是創(chuàng)建了一個(gè)新的集合來(lái)執(zhí)行操作
- 交集(Intersection):
交集是指兩個(gè)集合中共有的元素集合。在 Java 中,可以使用 retainAll 方法來(lái)實(shí)現(xiàn)兩個(gè)集合的交集操作。retainAll 方法會(huì)修改調(diào)用該方法的集合,使其只包含與指定集合共有的元素
源碼解析:
- Set
在AbstractCollection的 retainAll 方法的內(nèi)部實(shí)現(xiàn)中,通常會(huì)遍歷調(diào)用該方法的集合,并逐個(gè)判斷元素是否存在于指定集合中。如果元素不存在于指定集合,則通過(guò)迭代器的 remove 方法將其從集合中刪除。這樣就實(shí)現(xiàn)了只保留共有元素的操作。
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<E> it = iterator();
while (it.hasNext()) {
if (!c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
- ArrayList
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
- 并集(Union):
并集是指將兩個(gè)集合中的所有元素合并到一個(gè)新的集合中。在 Java 中,可以使用 addAll 方法來(lái)實(shí)現(xiàn)兩個(gè)集合的并集操作。addAll 方法會(huì)將指定集合中的所有元素添加到調(diào)用該方法的集合中。
- Set
addAll 方法的內(nèi)部實(shí)現(xiàn)會(huì)遍歷指定集合,并逐個(gè)將元素添加到調(diào)用該方法的集合中。如果被添加的元素已經(jīng)存在于集合中,則不會(huì)重復(fù)添加。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-699084.html
public boolean addAll(Collection<? extends E> c) {
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}
- ArrayList
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
- 差集(Difference):
差集是指從一個(gè)集合中移除另一個(gè)集合中相同的元素后的剩余元素集合。在 Java 中,可以使用 removeAll 方法來(lái)實(shí)現(xiàn)兩個(gè)集合的差集操作。removeAll 方法會(huì)修改調(diào)用該方法的集合,移除與指定集合相同的元素。
- Set
在 removeAll 方法的內(nèi)部實(shí)現(xiàn)中,通常會(huì)遍歷指定集合,并逐個(gè)判斷元素是否存在于調(diào)用該方法的集合中。如果元素存在于調(diào)用的集合中,則通過(guò)迭代器的 remove 方法將其從集合中移除。這樣就實(shí)現(xiàn)了移除與指定集合相同元素的操作。
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext()) {
if (c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
- ArrayList
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
/**
* Retains only the elements in this list that are contained in the
* specified collection. In other words, removes from this list all
* of its elements that are not contained in the specified collection.
*
* @param c collection containing elements to be retained in this list
* @return {@code true} if this list changed as a result of the call
* @throws ClassCastException if the class of an element of this list
* is incompatible with the specified collection
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if this list contains a null element and the
* specified collection does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see Collection#contains(Object)
*/
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
本文介紹了在 Java 中實(shí)現(xiàn)集合的交集、并集和差集操作的方法,并通過(guò)源碼解析來(lái)深入了解其實(shí)現(xiàn)原理。這些集合操作在實(shí)際開發(fā)中經(jīng)常使用,可以幫助我們處理集合數(shù)據(jù),快速進(jìn)行元素篩選和計(jì)算。掌握這些操作可以提高代碼的效率和可讀性。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-699084.html
到了這里,關(guān)于Java 集合操作之交集、并集和差集的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!