我有 3 个字符串列表
private @Getter @Setter List<String> allowedServicesId;
private @Getter @Setter List<String> notAllowedServicesId;
private @Getter @Setter List<String> replaceServiceId;
我需要检查这些列表中是否至少有一个对象的交集?
我创建了这个
for (String s : allowedServicesId) {
if (notAllowedServicesId.contains(s)){
throw new Exception("");
}
if (replaceServiceId.contains(s)){
throw new Exception("");
}
}
for (String s : notAllowedServicesId) {
if (replaceServiceId.contains(s)){
throw new Exception("");
}
}
但我认为这是不好的做法。我认为还有另一种方法。
编辑
我明白了
Set<String> set = new HashSet<>();
set.addAll(allowedServicesId);
set.addAll(notAllowedServicesId);
set.addAll(replaceServiceId);
int i = allowedServicesId.size() + notAllowedServicesId.size() + replaceServiceId.size();
if (set.size()!= i){
throw new Exception("");
}
像你一样?
编辑
我可以将List
更改为Set
private @Getter @Setter Set<String> allowedServicesId;
private @Getter @Setter Set<String> notAllowedServicesId;
private @Getter @Setter Set<String> replaceServiceId;
如果更简单
最佳答案
我认为您已经找到了一个可以接受的答案,即将三个列表添加到一个集合中。这是等效且更通用的 Java 8 代码
private static void assertForDuplicates(Collection<?>... collections) throws Exception {
int n = 0;
for (Collection<?> c : collections) {
n += c.size();
}
if (Stream.of(collections).flatMap(Collection::stream).collect(Collectors.toSet()).size() != n) {
throw new Exception();
}
}
关于java - 如何等于 3 ArrayList<String> 并检查此列表中对象的匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38607926/