java过滤集合,java – 如何通过交集过滤集合集合?

该博客介绍了一种用于合并多个集合交集的算法。它包含一个名为`mergeIntersections`的主要方法,该方法通过迭代和比较来合并集合,直到没有更多的交集可以合并。`isMergedSuccessfully`辅助方法检查是否所有集合已成功合并。示例代码展示了如何处理包含多个HashSet的集合,并在主函数中进行了测试。
摘要由CSDN通过智能技术生成

这应该解决你的用例.它可以以更有效的方式实现,但我想这应该给你一个开始的想法:

private static Collection> mergeIntersections(Collection> collection) {

Collection> processedCollection = mergeIntersectionsInternal(collection);

while (!isMergedSuccessfully(processedCollection)) {

processedCollection = mergeIntersectionsInternal(processedCollection);

}

return processedCollection;

}

private static boolean isMergedSuccessfully(Collection> processedCollection) {

if (processedCollection.size() <= 1) {

return true;

}

final Set mergedNumbers = new HashSet<>();

int totalNumbers = 0;

for (Set set : processedCollection) {

totalNumbers += set.size();

mergedNumbers.addAll(set);

}

if (totalNumbers > mergedNumbers.size()) {

return false;

}

return true;

}

private static Collection> mergeIntersectionsInternal(Collection> collection) {

final Collection> processedCollection = new ArrayList<>();

// ITERATE OVER ALL SETS

for (final Set numberSet : collection) {

for (final Integer number : numberSet) {

boolean matched = false;

// ITERATE OVER ALL PROCESSED SETS COLLECTION

for (final Set processedSet : processedCollection) {

// CHECK OF THERE IS A MATCH

if (processedSet.contains(number)) {

matched = true;

// MATCH FOUND, MERGE THE SETS

processedSet.addAll(numberSet);

// BREAK OUT OF PROCESSED COLLECTION LOOP

break;

}

}

// IF NOT MATCHED THEN ADD AS A COLLECTION ITEM

if (!matched) {

processedCollection.add(new HashSet<>(numberSet));

}

}

}

return processedCollection;

}

这是它执行它的方式:

public static void main(String[] args) {

final Collection> collection = new ArrayList<>();

final Set set1 = new HashSet<>();

set1.add(1);

set1.add(2);

set1.add(3);

collection.add(set1);

final Set set2 = new HashSet<>();

set2.add(4);

collection.add(set2);

final Set set3 = new HashSet<>();

set3.add(1);

set3.add(5);

collection.add(set3);

final Set set4 = new HashSet<>();

set4.add(4);

set4.add(7);

collection.add(set4);

final Set set5 = new HashSet<>();

set5.add(3);

set5.add(5);

collection.add(set5);

System.out.println(mergeIntersections(collection));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值