在 lambda 中获取索引 foreach 表达式 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);
});

此时无法获取索引,但无论如何都不支持修改要流式传输的list。当你尝试时,你可能会得到一个ConcurrentModificationException

使用专用 API 执行此操作:

list.removeIf(g -> g.getName().equalsIgnoreCase("String"));

另一种方法是将要保留的元素收集到新List中:

List<String> result = list.stream()
.filter(g -> !g.getName().equalsIgnoreCase("String"))
.collect(Collectors.toList());

你可以改用Collection#removeIf,例如:

list.removeIf(g -> g.getName().equalsIgnoreCase("String"));

抱歉,如果不能为您提供帮助

list.stream().filter(g->g.getName().equalsIgnoreCase("String")).forEach(result ->{
list.indexOf(result);
});