如何在 Java 中过滤非空值?


假设我们的 List 如下,其中包含字符串元素

List<String> leagues = Arrays.asList("BBL", "IPL", "MLB", "FPL","NBA", "NFL");

现在,创建一个流并过滤以特定字母结尾的元素

Stream<String> stream = leagues.stream().filter(leagueName -> leagueName.endsWith("L"));

现在,对非空值使用 Objects::nonnull

List<String> list = stream.filter(Objects::nonNull).collect(Collectors.toList());

以下是一个在 Java 中过滤非空值的示例

示例

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      List<String> leagues = Arrays.asList("BBL", "IPL", "MLB", "FPL","NBA", "NFL");
      Stream<String> stream = leagues.stream().filter(leagueName -> leagueName.endsWith("L"));
      List<String> list = stream.filter(Objects::nonNull).collect(Collectors.toList());
      System.out.println("League names ending with L = "+list);
   }
}

输出

League names ending with L = [BBL, IPL, FPL, NFL]

更新时间: 30-Jul-2019

2k+ 条浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告