Ank*_*dev 0 java foreach lambda arraylist java-8
我想从某个过滤器上的列表中删除对象,并且有多个对象.
list.stream().filter(g->g.getName().equalsIgnoreCase("String")).forEach(result ->{
/* is it possible to get the index of the result here?
.remove(), will iterate through the list again. I don't want that.
*/
list.remove(result);
});
Run Code Online (Sandbox Code Playgroud)
此时无法获得索引,但list无论如何都不支持修改流式传输.ConcurrentModificationException你尝试的时候可能会得到一个.
使用专用API执行此操作:
list.removeIf(g -> g.getName().equalsIgnoreCase("String"));
Run Code Online (Sandbox Code Playgroud)
另一种方法是收集你想要保留的新元素List:
List<String> result = list.stream()
.filter(g -> !g.getName().equalsIgnoreCase("String"))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6177 次 |
| 最近记录: |