
本文将深入探讨如何使用 Java Stream API 中的 distinct() 方法来检查列表中是否存在重复值,并解决在实际应用中可能遇到的 BadRequestException 异常。通过分析一个具体的代码示例,我们将找出问题根源,并提供相应的解决方案,确保列表去重操作的正确性和稳定性。
原始代码中使用 stream.distinct().count() != cheminementForm.getPositionsPoste().size() 来判断 positionsPoste 列表中是否存在重复值。虽然 distinct() 方法能够去除流中的重复元素,但如果列表中包含 null 值,则可能导致判断错误,从而抛出 BadRequestException 异常,即使列表中实际上没有重复的非空元素。
根本问题在于列表中可能包含 null 值,而原始代码没有对 null 值进行处理。因此,在进行重复值判断之前,需要先从列表中移除 null 值。可以使用 filter() 方法过滤掉 null 元素。
以下是修改后的代码:
if(cheminementForm.getPositionsPoste().stream().filter(Objects::nonNull).distinct().count() != cheminementForm.getPositionsPoste().stream().filter(Objects::nonNull).count()){
throw new BadRequestException("Cannot have same positions");
}代码解释:
完整代码示例:
public Cheminement add(final CheminementForm cheminementForm) throws BadRequestException {
if(cheminementForm == null){
log.error("Cheminement can not be null");
throw new BadRequestException("CheminementForm can not be null");
}else if (Objects.isNull(cheminementForm.getName())){
log.error("All fields must be filled.");
throw new BadRequestException("All fields must be filled.");
}
Cheminement cheminement = Cheminement.builder().disable(false).name(cheminementForm.getName()).build();
List<CheminementEtape> cheminementEtapeList = new ArrayList<>();
List<Integer> positionsPoste = cheminementForm.getPositionsPoste();
if(positionsPoste != null && positionsPoste.stream().filter(Objects::nonNull).distinct().count() != positionsPoste.stream().filter(Objects::nonNull).count()){
throw new BadRequestException("Cannot have same positions");
}
for(int i=0; i<cheminementForm.getEtapes().size(); i++){
if(cheminementForm.getPositionsPoste().get(i) < 0 ){
throw new BadRequestException("position cannot be null");
}
cheminementEtapeList.add(CheminementEtape.builder().cheminement(cheminement).etape(cheminementForm.getEtapes().get(i)).positionPoste(cheminementForm.getPositionsPoste().get(i)).disable(false).build());
}
cheminementRepository.save(cheminement);
cheminementEtapeService.add(cheminementEtapeList);
return cheminement;
}使用 Stream.distinct() 方法检查列表是否存在重复值时,需要特别注意列表中可能存在的 null 值。通过在去重之前使用 filter() 方法过滤掉 null 元素,可以避免因 null 值导致的判断错误。同时,建议在前端或后端对输入数据进行校验,从根本上保证数据的质量。此外,根据实际情况选择合适的去重算法,以提高程序的性能。
以上就是使用 Stream.distinct() 检查列表是否存在重复值的正确方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号