Java 8 streams/maps/filters to modify or delete list elements on the fly
Because you are using void
as return type and want to modify the given List using a Stream would not be the best solution. You can just use List.replaceAll()
and List.removeIf()
to solve this with a simple if
statement:
public void applyChanges(List<Fizz> fizzes, Action action, Fizz toModify) {
if (action == Action.Replace) {
fizzes.replaceAll(fizz -> fizz.getId() == toModify.getId() ? toModify : fizz);
} else {
fizzes.removeIf(fizz -> fizz.getId() == toModify.getId());
}
}
If you have more actions than replace and delete you can use a switch
statement instead of if
.
If you really want to use Streams I also would separate the different actions. You also have to return the new List in your method and reassign it to the variable you pass to that method:
public List<Fizz> applyChanges(List<Fizz> fizzes, Action action, Fizz toModify) {
if (action == Action.Replace) {
return fizzes.stream()
.map(fizz -> fizz.getId() == toModify.getId() ? toModify : fizz)
.collect(Collectors.toList());
}
return fizzes.stream()
.filter(fizz -> fizz.getId() != toModify.getId())
.collect(Collectors.toList());
}
You can use map
with streams something like :
List<Fizz> applyChanges(List<Fizz> fizzes, Action action, Fizz toModify) {
return fizzes.stream()
.map(fizz -> fizz.getId().equals(toModify.getId()) ?
action.equals(Action.Replace) ? toModify : null : fizz)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}