• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

Java 8 Streams filter

java8 来源:石奈子 1次浏览

在这篇教程中,我们将用少量的例子向你展示java8中的Streams filter(), collect(), findAny() and orElse().

  • Streams filter() 和 collect()

    • Java 8之前, 过滤一个集合是这样的 :

      BeforeJava8.java
      package com.ricky.java8;
      
      import java.util.ArrayList;
      import java.util.Arrays;
      import java.util.List;
      
      public class BeforeJava8 { 
      
          public static void main(String[] args) {
      
              List<String> lines = Arrays.asList("spring", "node", "ricky");
              List<String> result = getFilterOutput(lines, "ricky");
              for (String temp : result) {
                  System.out.println(temp);    //output : spring, node
              }
      
          }
      
          private static List<String> getFilterOutput(List<String> lines, String filter) {
              List<String> result = new ArrayList<>();
              for (String line : lines) {
                  if (!"ricky".equals(line)) { // we dont like ricky
                      result.add(line);
                  }
              }
              return result;
          }
      
      }
    • 输出

      spring
      node
    • 1.2 java8中等价的例子,使用stream.filter()去过滤集合,使用collect()将stream转化为一个集合。

    NowJava8.java
    package com.ricky.java8;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class NowJava8 { 
    
        public static void main(String[] args) {
    
            List<String> lines = Arrays.asList("spring", "node", "ricky");
    
            List<String> result = lines.stream()                // convert list to stream
                    .filter(line -> !"ricky".equals(line))     // we dont like ricky
                    .collect(Collectors.toList());              // collect the output and convert streams to a List
    
            result.forEach(System.out::println);                //output : spring, node
    
        }
    
    }

    -输出

    spring
    node
  • Streams filter(), findAny() and orElse()

Person.java
package com.ricky.java8;

public class Person { 

    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    //gettersm setters, toString
}
  • Java 8之前, 你获取Person的name是这样的 :
 BeforeJava8.java
        package com.ricky.java8;

        import java.util.Arrays;
        import java.util.List;

        public class BeforeJava8 { 

            public static void main(String[] args) {

                List<Person> persons = Arrays.asList(
                        new Person("ricky", 30),
                        new Person("jack", 20),
                        new Person("lawrence", 40)
                );

                Person result = getStudentByName(persons, "jack");
                System.out.println(result);

            }

            private static Person getStudentByName(List<Person> persons, String name) {

                Person result = null;
                for (Person temp : persons) {
                    if (name.equals(temp.getName())) {
                        result = temp;
                    }
                }
                return result;
            }
        }
输出

```java
Person{name='jack', age=20}

```
  • 等价的java8列子,使用stream.filter()过滤集合, .findAny().orElse (null)返回一个符合条件的对象。

    NowJava8.java
        package com.ricky.java8;
    
        import java.util.Arrays;
        import java.util.List;
    
        public class NowJava8 { 
    
            public static void main(String[] args) {
    
                List<Person> persons = Arrays.asList(
                        new Person("ricky", 30),
                        new Person("jack", 20),
                        new Person("lawrence", 40)
                );
    
                Person result1 = persons.stream()                        // Convert to steam
                        .filter(x -> "jack".equals(x.getName()))        // we want "jack" only
                        .findAny()                                      // If 'findAny' then return found
                        .orElse(null);                                  // If not found, return null
    
                System.out.println(result1);
    
                Person result2 = persons.stream()
                        .filter(x -> "ahmook".equals(x.getName()))
                        .findAny()
                        .orElse(null);
    
                System.out.println(result2);
    
            }
    
        }
    

    输出

    Person{name='jack', age=20}
        null
    • 多种条件
      NowJava8.java
          package com.ricky.java8;
      
          import java.util.Arrays;
          import java.util.List;
      
          public class NowJava8 { 
      
              public static void main(String[] args) {
      
                  List<Person> persons = Arrays.asList(
                          new Person("ricky", 30),
                          new Person("jack", 20),
                          new Person("lawrence", 40)
                  );
      
                  Person result1 = persons.stream()
                          .filter((p) -> "jack".equals(p.getName()) && 20 == p.getAge())
                          .findAny()
                          .orElse(null);
      
                  System.out.println("result 1 :" + result1);
      
                  //or like this
                  Person result2 = persons.stream()
                          .filter(p -> {
                              if ("jack".equals(p.getName()) && 20 == p.getAge()) {
                                  return true;
                              }
                              return false;
                          }).findAny()
                          .orElse(null);
      
                  System.out.println("result 2 :" + result2);
      
              }
      
      
          }
  • 输出

    result 1 :Person{name='jack', age=20}
        result 2 :Person{name='jack', age=20}
    • Streams filter() and map()
NowJava8.java
package com.ricky.java8;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class NowJava8 { 

    public static void main(String[] args) {

        List<Person> persons = Arrays.asList(
                new Person("ricky", 30),
                new Person("jack", 20),
                new Person("lawrence", 40)
        );

        String name = persons.stream()
                .filter(x -> "jack".equals(x.getName()))
                .map(Person::getName)                        //convert stream to String
                .findAny()
                .orElse("");

        System.out.println("name : " + name);

        List<String> collect = persons.stream()
                .map(Person::getName)
                .collect(Collectors.toList());

        collect.forEach(System.out::println);

    }

}
  • 输出

    name : jack
    
    ricky
    jack
    lawrence

翻译

ricky 20170728

交流群:244930845


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)