App下載
首頁(yè)javastream_filterJava Stream - 如何map對(duì)象獲取一個(gè)屬性,然后過(guò)濾并獲取前10個(gè),最后輸出

Java Stream - 如何map對(duì)象獲取一個(gè)屬性,然后過(guò)濾并獲取前10個(gè),最后輸出

我們想知道如何map對(duì)象獲取一個(gè)屬性,然后過(guò)濾并獲取前10個(gè),最后輸出。
import java.util.Arrays;
import java.util.List;


public class Main{
  public static void main(String[] argv){
    List<Person> persons = Arrays.asList(new Person("HTML", 12), new Person("Aim", 34), new Person("John", 23));
    persons.stream()
            .map(Person::getFirstName)
            .filter(name -> name.startsWith("A"))
            .limit(10)
            .forEach(name -> System.out.println(name));
  }
}
class MyWrapper {
  private Person person;

  public MyWrapper(Person person) {
      this.person = person;
  }

  public Person getPerson() {
      return person;
  }

  public void setPerson(Person person) {
      this.person = person;
  }
}
class Person {
    private String firstName;
    private String lastName;
    private int age;

    public Person(String firstName) {
        this.firstName = firstName;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
      return "Person [firstName=" + firstName + ", lastName=" + lastName
          + ", age=" + age + "]";
    }
    
}