0

如果我有集合集合。而且我必须在 Collection 中找到相同的对,即:

收藏:

  • 设置 {Object_A,Object_B,Object_C}
  • 设置 {Object_A、Object_B、Object_F}

如何在 Collection> 中找到对:Object_A-Object_B?可以为此目的使用什么 Java 库?

4

3 回答 3

0

如果你想使用一个库,你可以使用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 文档以获取更多详细信息和替代方案。

于 2013-09-04T13:13:44.703 回答
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 );

      }
}
于 2013-09-04T11:42:35.650 回答
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);
于 2013-09-04T11:26:22.770 回答