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

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

How to filter and log null objects in Java 8 streams

问题

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

在旧版Java中,

List<Obj> newObjs = new ArrayList<Obj>();
for (Obj obj : objects) {
    if (obj == null) {
        logger.error("null object");
    } else {
        newObjs.add(...);
    }
}

基本上,我想要过滤掉空对象并将其记录到日志中。
在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,

List&lt;Obj&gt; newObjs = ArrayList&lt;Obj&gt;();
for (Obj obj : objects){
  if(obj == null){
     logger.error(&quot;null object&quot;);
  }
  else{
    newObjs.add(...)
  }
}

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

答案1

得分: 5

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

public boolean filter(Object obj) {
    if (obj == null) {
        logger.error("null object");
        return false;
    }
    return true;
}

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

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

I would suggest to move that logic into different method

public boolean filter(Object obj) {

  if(obj == null){
      logger.error(&quot;null object&quot;);
      return false;
    }
  return true;
}

And then just stream the list

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

答案2

得分: 4

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

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

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

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

英文:

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

List&lt;Obj&gt; newObjs = objects.stream().peek(x -&gt; {
    if (x == null) logger.error(&quot;null object&quot;);
}).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:

确定