英文:
How to stream the removed items in java removeIf?
问题
我正在使用 removeIf
方法从列表中移除名称或代码为空的特定对象:
tables.removeIf(t -> ((t.getName() == null) || (t.getCode() == null)));
我是否能够获取在此处实际已被移除的项目 t
?也许可以获得已移除项目的列表,或者更好的是,已移除项目的流?
谢谢
英文:
I'm using removeIf
to remove certain objects from a list if their name or code is null:
tables.removeIf(t -> ((t.getName() == null) || (t.getCode() == null)));
Is there a way I can get the actual items t
that have been removed here? Maybe a list of the removed items, or better yet, a stream of the removed items?
Thanks
答案1
得分: 6
你可以根据你的标准进行分区,然后将结果用于你想要的任何操作:
Map<Boolean, List<MyClass>> split = tables.stream()
.collect(Collectors.partitioningBy(t ->
t.getName() == null || t.getCode() == null));
List<MyClass> cleanList = split.get(Boolean.FALSE);
List<MyClass> removedList = split.get(Boolean.TRUE);
cleanList
包含了在执行 removeIf
操作后 tables
中所包含的内容,而 removedList
则包含了被丢弃的数据(你要查找的数据)。
英文:
You can partition by your criterion and then use the result for whatever you want:
Map<Boolean, List<MyClass>> split = tables.stream()
.collect(Collectors.partitioningBy(t ->
t.getName() == null || t.getCode() == null));
List<MyClass> cleanList = split.get(Boolean.FALSE);
List<MyClass> removedList = split.get(Boolean.TRUE);
cleanList
contains what tables
would have contained after removeIf
, and removedList
data that was discarded (the one you were looking for)
答案2
得分: 3
将它分为两个步骤:
第一步,找到需要移除的对象:
List<ObjectName> toBeRemoved = tables.stream()
.filter(t -> t.getName() == null || t.getCode() == null)
.collect(Collectors.toList());
第二步,从列表中移除它们:
tables.removeAll(toBeRemoved);
英文:
What about make it in two steps :
find objects you want to remove:
List<ObjectName> toBeRemoved = tables.stream()
.filter(t -> t.getName() == null || t.getCode() == null)
.collect(Collectors.toList());
and then remove them from the list :
tables.removeAll(toBeRemoved);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论