我有两个EnumSet
s。
EnumSet.of(A1, A2, A3);
EnumSet.of(A3, A4, A5, A6);
我想找出两组中都存在哪些值。(在这种情况下,A3
。)
有什么快速的方法吗?
我有两个EnumSet
s。
EnumSet.of(A1, A2, A3);
EnumSet.of(A3, A4, A5, A6);
我想找出两组中都存在哪些值。(在这种情况下,A3
。)
有什么快速的方法吗?
EnumSet
是一个集合。因此,您可能可以使用retainAll方法来获取交集。
仅保留此集合中包含在指定集合中的元素(可选操作)。换句话说,从这个集合中移除所有不包含在指定集合中的元素。如果指定的集合也是一个集合,则此操作有效地修改此集合,使其值是两个集合的交集。
请注意,这将修改现有集合。如果你不想这样,你可以创建一个副本。如果这对您来说不是一个好的选择,您可以寻找其他解决方案。
EnumSet A = EnumSet.of(A1, A2, A3);
EnumSet B = EnumSet.of(A3, A4, A5, A6);
EnumSet intersection = EnumSet.copyOf(A);
intersection.retainAll(B);
retainAll
修改基础集,因此创建一个副本。
由于EnumSets
是 的子类型Iterable
,因此您可以使用CollectionUtils
Apaches Collections(经常使用的第三方库)。
CollectionUtils.intersection (
EnumSet.of (A1, A2, A3),
EnumSet.of (A3, A4, A5, A6)
);
您可以在 java 8 中使用 Streams API:
Set set1 = EnumSet.of(A1, A2, A3); // add type argument to set
Set set2 = EnumSet.of(A3, A4, A5, A6); // add type argument to set
set2.stream().filter(set1::contains).forEach(a -> {
// Do something with a (it's in both sets)
});