Java 8 Streams filter

石奈子發表於2017-07-30

在這篇教程中,我們將用少量的例子向你展示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

相關文章