使用流更改ArrayList中对象的字段值,使代码更有效

Bla*_*dan 2 java object java-8 java-stream

我内部ArrayList有一个有限数量的对象。我想在列表中查找字段中的特定值,然后进行更改。

我有以下实现。

String searchName = searchedName; //from outside we provide this
Person person = personList.stream()
        .filter(personList -> searchName.equals(personList.getName()))
        .findFirst()
        .orElse(null);
if (person != null){
    person.setName(replacement);
}
Run Code Online (Sandbox Code Playgroud)

这段代码可以工作,但是流不是我的专长,我的问题是:我是否可以具有相同的行为,而不必付出额外的代价呢?我觉得“如果”是多余的东西,我想使我的代码更有效。

附带的问题是,如果我们有多个具有相同名称的条目,则有一种使用流的方法,因此,除了“ .findFirst().orElse(null)”之外,我还可以使用哪种方法将其存储在person对象或可能的new对象中对象数组。

And*_*cus 5

您可以使用Optional#isPresent以下代码减少代码:

personList.stream()
          .filter(personList -> searchName.equals(personList.getName()))
          .findFirst()
          .ifPresent(person -> person.setName(replacement));
Run Code Online (Sandbox Code Playgroud)

但是,如果我追求性能,那么流并不是我的首选。

如果要处理所有对象,则可以满足谓词:

personList.stream()
          .filter(personList -> searchName.equals(personList.getName()))
          .forEach(person -> person.setName(replacement));
Run Code Online (Sandbox Code Playgroud)

  • @BlajBogdan注意,此答案的解决方案没有“ Person person =…”分配。使用此答案中所写的代码,但两个点除外。 (2认同)