java集合去空(list去空)

今天新任职一家公司,下面是自己写的集合去空

public static void main(String[] args) {
          
   
        List<String> list = Arrays.asList("ye", "chuan", null);
        List<String> collect = list.stream().map(e -> {
          
   
            if (e == null) {
          
   
                return null;
            }
            return e;
        }).collect(Collectors.toList());
        System.out.println(collect);//[ye, chuan, null]
      collect.removeAll(Collections.singleton(null));
        System.out.println(collect);//[ye, chuan]
    }

下面是公司十几年技术大牛写的集合去空

public static void main(String[] args) {
          
   
        List<String> list = Arrays.asList("ye", "chuan", null);
        List<String> collect = list.stream().map(e -> {
          
   
            if (e == null) {
          
   
                return null;
            }
            return e;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        System.out.println(collect);//[ye, chuan]
    }

其实感觉都差不多,但是还是感觉自己的代码不如别人的,不知道为什么 意志以为流的.filter方法是过滤自己想要的数据,原来可以去除不想要的数据 感觉自己对jdk8流的写法运用少了。

青海长云暗雪山,孤城遥望玉门关。 黄沙百战穿金甲,不破楼兰终不还!

奥里给 开干

经验分享 程序员 微信小程序 职场和发展