如何在Java的`removeIf`中流式传输已删除的项?

huangapple go评论60阅读模式
英文:

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&lt;Boolean, List&lt;MyClass&gt;&gt; split = tables.stream()
     .collect(Collectors.partitioningBy(t -&gt; 
                t.getName() == null || t.getCode() == null));

List&lt;MyClass&gt; cleanList = split.get(Boolean.FALSE);
List&lt;MyClass&gt; 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&lt;ObjectName&gt; toBeRemoved = tables.stream()
        .filter(t -&gt; t.getName() == null || t.getCode() == null)
        .collect(Collectors.toList());

and then remove them from the list :

tables.removeAll(toBeRemoved);

huangapple
  • 本文由 发表于 2020年10月21日 00:10:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64449117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定