Java Stream API校验请求字段与SharePoint列时抛异常的实现方案
实现方案
前置处理
首先提前提取请求的字段名集合,避免重复遍历请求字段,同时预定义允许的通用分组:
// 提取请求中的所有字段名,用于O(1)判断存在性 Set<String> requestFieldNames = request.getFields().stream() .map(RequestField::getName) // 替换为你实际的Field类取名字段的方法 .collect(Collectors.toSet()); int totalRequestFields = requestFieldNames.size(); // 预定义通用分组,可根据业务调整 Set<String> COMMON_ALLOWED_GROUPS = Set.of("System", "Global", "通用配置"); String targetDocType = request.getDocumentType();
核心校验逻辑
仅需一次遍历SharePoint返回的列,即可同时完成字段存在性校验、分组匹配校验,无需多余的流处理和集合转换:
AtomicInteger validMatchedColumnCount = new AtomicInteger(0); sharePointDriveResponse.getColumns().stream() // 过滤出和请求字段匹配的列 .filter(column -> requestFieldNames.contains(column.getDisplayName())) // 校验分组是否合法,不合法直接抛出异常 .peek(column -> { String columnGroup = column.getColumnGroup(); boolean groupValid = COMMON_ALLOWED_GROUPS.contains(columnGroup) || targetDocType.equals(columnGroup); if (!groupValid) { throw new RequestException(String.format("字段[%s]所属分组[%s]不匹配当前文档类型", column.getDisplayName(), columnGroup)); } }) // 合法匹配列计数+1 .forEach(column -> validMatchedColumnCount.incrementAndGet()); // 校验所有请求字段都有对应合法列 if (validMatchedColumnCount.get() != totalRequestFields) { throw new RequestException("存在请求字段不在SharePoint列配置中"); } // 所有校验通过 System.out.println("校验通过");
问题解答
- Stream内直接抛异常:上述代码在
peek操作中只要检测到分组不合法就会立即抛出异常,无需等全量集合收集完成再判断。如果希望把字段不存在的校验也合并到流逻辑中,可在计数后用IntStream判断:
IntStream.of(validMatchedColumnCount.get()) .filter(cnt -> cnt != totalRequestFields) .findAny() .ifPresent(cnt -> { throw new RequestException("存在请求字段不在SharePoint列配置中"); });
- 避免重复遍历:全程仅遍历一次SharePoint返回的列集合,没有多余的流创建和集合转换操作,性能最优。
- 通用分组兼容:代码中已经将通用分组的判断逻辑加入分组校验规则,只要属于预定义的通用分组列表,就不受当前请求的documentType限制。
Java 12+ 简化实现
如果使用Java 12及以上版本,可借助Collectors.teeing进一步简化为纯函数式写法,无需额外的原子类计数:
Long validCount = sharePointDriveResponse.getColumns().stream() .filter(col -> requestFieldNames.contains(col.getDisplayName())) .collect(Collectors.teeing( Collectors.counting(), Collectors.filtering( col -> !(COMMON_ALLOWED_GROUPS.contains(col.getColumnGroup()) || targetDocType.equals(col.getColumnGroup())), Collectors.findFirst() ), (count, invalidCol) -> { if (invalidCol.isPresent()) { throw new RequestException(String.format("字段[%s]所属分组不合法", invalidCol.get().getDisplayName())); } return count; } )); if (validCount != totalRequestFields) { throw new RequestException("存在请求字段不在SharePoint列配置中"); }
内容的提问来源于stack exchange,提问作者davidvera
相关产品推荐
相关产品推荐

