Mea*_*ell 4 java set java-stream
假设我有一个非常简单的类 Person,其中包含名称和地址:
public class Person {
String name;
String address;
public Person(final String name,
final String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(final String newName) {
this.name = newName;
}
public String address() {
return address;
}
public void setAddress(final String newAddress) {
this.address = newAddress;
}
}
Run Code Online (Sandbox Code Playgroud)
我现在有一个包含所有已知 Person 对象的 Set,并且我想仅根据其中一个人的姓名来更新他们的地址。为此,我有以下几点:
persons.stream()
.filter(person -> personToUpdate.getName().equalsIgnoreCase(person.getName()))
.forEach(person -> {
person.setAddress(personToUpdate.getAddress());
});
Run Code Online (Sandbox Code Playgroud)
然而,我的问题是当我有一个完全不在集合中的新人时。如何检查该集合以查看此人是否存在,如果存在,请更新其地址。但如果它们不存在,请将它们添加到列表中。我知道这很简单,但无论出于何种原因,我现在都不知道如何实现这一目标。我不想继续创建所有名称的列表,比较新名称,如果它们在列表中等等。我宁愿保持尽可能简洁。
编辑:名称将是唯一的!
Unless you need a one-liner, you can simply take advantage of the of the Optionals:
Optional<Person> person = persons.stream()
.filter(p -> personToUpdate.getName().equalsIgnoreCase(p.getName()))
.findFirst();
if (person.isPresent()) {
person.get().setAddress(personToUpdate.getAddress());
} else {
persons.add(personToUpdate);
}
Run Code Online (Sandbox Code Playgroud)
If you're using Java 9+, this can look even better:
persons.stream()
.filter(p -> personToUpdate.getName().equalsIgnoreCase(p.getName()))
.findFirst()
.ifPresentOrElse(
p -> p.setAddress(personToUpdate.getAddress()),
() -> persons.add(personToUpdate)
);
Run Code Online (Sandbox Code Playgroud)
This of course assumes that names are unique (as you expect to update one entry).