gts*_*s13 7 java collections enums enumset
我有两个EnumSet
.
EnumSet.of(A1, A2, A3);
EnumSet.of(A3, A4, A5, A6);
Run Code Online (Sandbox Code Playgroud)
我想找到两个集合中存在哪些值.(在这种情况下,A3
.)
有没有快速的方法呢?
由于EnumSets
是子类型Iterable
,您可以使用CollectionUtils
Apaches Collections(通常使用的第三方库).
CollectionUtils.intersection (
EnumSet.of (A1, A2, A3),
EnumSet.of (A3, A4, A5, A6)
);
Run Code Online (Sandbox Code Playgroud)
小智 7
EnumSet A = EnumSet.of(A1, A2, A3);
EnumSet B = EnumSet.of(A3, A4, A5, A6);
EnumSet intersection = EnumSet.copyOf(A);
intersection.retainAll(B);
Run Code Online (Sandbox Code Playgroud)
retainAll
修改基础集,以便创建副本.
您可以在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)
});
Run Code Online (Sandbox Code Playgroud)