The use of Java 8 stream().filter() filter

demand

Now there is such a demand that some data is stored in a list array, and I want to retrieve the data under certain conditions. For example, I want to retrieve students who are over 10 years old, and for example, I want to retrieve some information about Zhang San.

Ideas to solve

If you want to get some data in a set of lists, it is to filter the data. Our native method is to traverse the list array, and then make a judgment, and come up with the data of the corresponding conditions. This is a very troublesome method, so a very simple method appeared in Java 8, the filter. Only need a very simple line, you can get the data you want.

Specific code explanation

package com.cc;

public class Person {
    
    

    private String name;

    private Integer age;


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

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public Integer getAge() {
    
    
        return age;
    }

    public void setAge(Integer age) {
    
    
        this.age = age;
    }
}



package com.cc;

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

public class streamTest {
    
    
    public static void main(String[] args) {
    
    

        Person[] person = {
    
    new Person("moon",18), new Person("cc",3)};

        //将数组转成list
        List<Person> list = Arrays.asList(person);

        //一个条件筛选
        Person result1 = list.stream().filter(p -> "moon".equals(p.getName()))
                .findAny().orElse(null);//如果找不到数据会返回null。orElse()是设置找不到数据后的默认值。
        System.out.println(result1.getName());  //moon


        //多个条件筛选
        Person result2 = list.stream().filter(p -> "oo".equals(p.getName()) && 18 == p.getAge())
                .findAny().orElse(new Person("liang", 20));
        System.out.println(result2.getName());  //liang


        String name = list.stream().filter(p -> "moon".equals(p.getName())).map(Person::getName)
                .findAny().orElse("");  // moon
        System.out.println(name);


        List<String> names = list.stream().filter(p -> "moon".equals(p.getName())).map(Person::getName)
                .collect(Collectors.toList());
        names.forEach(System.out::println);   //moon
        
    }
}

to sum up

Using filters can easily select data that meets specific conditions, and it also reduces the amount of code.

supplement

Now I want to extract the name column, so what should I do?

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

Guess you like

Origin blog.csdn.net/hello_cmy/article/details/108064582