如何使用 Java 流来映射项目

DDS*_*low 0 java java-stream

我是 Java 新手,开始学习java streams. 我已经理解了filter如何使用流,但是理解map正在成为一个挑战。

我有一个Person.java代码

public class Person {

    // Fields
    private String name;
    private int age;
    private String gender;

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

    // Getters
    public String getName() {
        return this.name;
    }
    public int getAge() {
        return this.age;
    }
    public String getGender() {
        return this.gender;
    }

    // Setters
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }

}
Run Code Online (Sandbox Code Playgroud)

Streams.java作为

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


public class Streams {

    public static void main(String[] args) {
        final List <Person> people = getPeople();

        // Map
        System.out.println("Map using Streams | Increase Everyone's Age by 10:");
        List <Person> persons = people.stream()
            // this part is failing
            .map(person -> person.setAge(person.getAge() + 10))
            .collect(Collectors.toList()
        );
        persons.forEach(
            person ->
            System.out.printf("%s: %d\n", person.getName(), person.getAge())
        );

    }

    private static List<Person> getPeople() {
        return List.of(
            new Person("Female-Kid", 10, "female"),
            new Person("Male-Young", 21, "male"),
            new Person("Male-Mid", 34, "male"),
            new Person("Female-Old", 100, "female")
        );
    }
}

Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我有一个列表<Person>,我想将每个人的年龄增加 10,但是上面的代码失败并且不正确。

有人可以让我知道正确的实施吗?

干杯,DD

小智 8

使用forEach这里的方法比使用map. Map 用于将一段数据转换为另一段数据,forEach 用于对流的每个元素执行操作,这就是这里发生的情况。

  • 附录:当使用不可变的“Person”类型和创建具有更改年龄的新“Person”实例的函数时,使用“map”是合适的。 (3认同)