I have say a list of Person. I have to iterate over this list to find the person with id X, if found, I have to update some attribute on the person:
persons.stream() .filter(person -> "A11".equals(person.getId())) .findAny() .map(person -> { person.setSomeField("some-value"); return person; });
This code snippet is working for me, bu I’m not sure it’s clear enough what this is trying to achieve, I’m using that .map whose return value I don’t really need so I was wondering if there’s a better way to do this?
Advertisement
Answer
The simple solution to find all the person with some given id will be. Foreach them set the field.
persons.stream().filter(p -> "id".equalsIgnoreCase(p.getId())).forEach(person -> person.setSomeField("some-value"));