我是 Java 新手,开始学习
java streams
。我已经理解了使用流的 filter
ation,但是,理解 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;
}
}
和
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")
);
}
}
在上面的代码中,我有一个列表
<Person>
,我想将每个人的年龄增加10,但是上面的代码失败并且不正确。
有人可以让我知道正确的实现吗。
干杯, DD
Stream.map()
接受Function
接口的实例。问题是,很可能 person.setAge()
返回 void
,因此 javac
(Java 最著名的编译器,很可能你正在使用它),试图推断 lambda 中使用的确切 功能接口 ,无法推断 Function
,因为 setAge
返回 void
。为了修复它,让 setAge
返回这个,例如:
public Person setAge(int age) {
this.age = age;
return this;
}