如何在Java 8流中筛选和记录空对象

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

How to filter and log null objects in Java 8 streams

问题

我正努力理解Java 8的流(Streams)并想知道是否有人可以帮助我。

在旧版Java中,

  1. List<Obj> newObjs = new ArrayList<Obj>();
  2. for (Obj obj : objects) {
  3. if (obj == null) {
  4. logger.error("null object");
  5. } else {
  6. newObjs.add(...);
  7. }
  8. }

基本上,我想要过滤掉空对象并将其记录到日志中。
在Java 8中有什么好的方法可以做到这一点?

英文:

I am trying to wrap my head around java8 streams and was wondering if someone can help me with it.

In old java,

  1. List&lt;Obj&gt; newObjs = ArrayList&lt;Obj&gt;();
  2. for (Obj obj : objects){
  3. if(obj == null){
  4. logger.error(&quot;null object&quot;);
  5. }
  6. else{
  7. newObjs.add(...)
  8. }
  9. }

Basically, I want to filter null objects and also log it.
What's a good way to do this in java 8?

答案1

得分: 5

我建议将该逻辑移到不同的方法中。

  1. public boolean filter(Object obj) {
  2. if (obj == null) {
  3. logger.error("null object");
  4. return false;
  5. }
  6. return true;
  7. }

然后只需对列表进行流处理。

  1. objects.stream().filter(this::filter).collect(Collectors.toList());
英文:

I would suggest to move that logic into different method

  1. public boolean filter(Object obj) {
  2. if(obj == null){
  3. logger.error(&quot;null object&quot;);
  4. return false;
  5. }
  6. return true;
  7. }

And then just stream the list

  1. objects.stream().filter(this::filter).collect(Collectors.toList());

答案2

得分: 4

你可以使用 peek 方法,并在其中放置一个 if 语句:

  1. List<Obj> newObjs = objects.stream().peek(x -> {
  2. if (x == null) logger.error("null object");
  3. }).filter(Objects::nonNull).collect(Collectors.toList());

但这种方式会使流失去简洁性,所以个人而言,对于像“过滤空对象并收集到列表中”这样的简单操作,我仍然会使用普通的 for 循环。

请记住,流 不能 替代 for 循环。不要仅仅因为流是新的和时髦的就使用它们。

英文:

You can use peek and put an if statement inside it:

  1. List&lt;Obj&gt; newObjs = objects.stream().peek(x -&gt; {
  2. if (x == null) logger.error(&quot;null object&quot;);
  3. }).filter(Objects::nonNull).collect(Collectors.toList());

But this kind of loses the conciseness of the streams, so personally I would still use a plain old for loop for something simple like "filtering nulls and collecting to a list".

Keep in mind that Streams do not replace for loops. Don't use streams just because it's new and shiny.

huangapple
  • 本文由 发表于 2020年8月19日 10:37:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63479228.html
匿名

发表评论

匿名网友

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

确定