如果我有Set的集合。我必须在Collection中找到相同的对, 即:
收集:
如何在Collection>中找到pair:Object_A-Object_B? ? 什么Java库可以用于此目的?
答案 0 :(得分:0)
Set<String> setA = new HashSet<>(Arrays.asList("one", "two", "three"));
Set<String> setB = new HashSet<>(Arrays.asList("one", "two", "four"));
Set<String> intersection = new HashSet<>(setA);
intersection.retainAll(setB);
System.out.println("intersection: " + intersection);
答案 1 :(得分:0)
以下示例将有所帮助。
import java.util.Collection;
import java.util.HashSet;
import java.util.Arrays;
class Identical {
public static void main( String [] args ) {
Collection<String> listOne = Arrays.asList("Object_A","Object_B",
"Object_C");
Collection<String> listTwo = Arrays.asList("Object_A","Object_B",
"Object_F");
Collection<String> similar = new HashSet<String>( listOne );
Collection<String> different = new HashSet<String>();
different.addAll( listOne );
different.addAll( listTwo );
similar.retainAll( listTwo );
different.removeAll( similar );
}
}
答案 2 :(得分:0)
如果您想使用lib,可以使用 Google Guava ,只需调用:
Sets.intersection(setOne, setTwo);
请参阅Sets
.
intersection()
。
例如:
Sets.SetView<String> intersectionView = Sets.intersection(
ImmutableSet.of("Object_A", "Object_B", "Object_C"),
ImmutableSet.of("Object_A", "Object_B", "Object_D"));
Set<String> intersectionSet = intersectionView.immutableCopy();
intersectionView
将仅作为"Object_A"
和"Object_B"
视图作为元素,由两个原始集支持。 intersectionSet
将是一个不可变的交集。
根据您的需求(可变性等),请参阅Guava文档以获取更多详细信息和替代方案。