Java 中使用 Stream 删除 ArrayList 元素的最佳实践
在使用 Stream 删除 ArrayList 元素时,您可能会遇到 s->s.getId() 返回一个 Integer 对象而不是 int 原始类型的情况。以下两种方法可以解决此问题:
- 使用
intValue()方法:
@DeleteMapping("/{id}")
public void delete(@PathVariable int id){
this.arrayList= this.arrayList.stream().filter(s->s.getId().intValue()==id).collect(Collectors.toList());
}
- 使用
equals()方法:
@DeleteMapping("/{id}")
public void delete(@PathVariable int id){
this.arrayList= this.arrayList.stream().filter(s->s.getId().equals(id)).collect(Collectors.toList());
}
这两种方法都可以在比较 Integer 对象和 int 值时提供正确的结果。建议根据您的代码风格和具体场景选择合适的方法。
原文地址: https://www.cveoy.top/t/topic/pkxV 著作权归作者所有。请勿转载和采集!