I have the following code and it works using the good old java:
List<Bar> repo = ArrayList<>();
public Bar foo(int id) {
for(Bar c: repo){
if(c.getId() == id)
return c;
}
Bar target = new Bar();
target.setFooo("");
target.setId(0);
return target;
}
However, I was trying to make it a little better, (i.e. just trying to learn lambdas)
public Bar foo(int id) {
Bar target = repo.stream().filter(c -> c.getId() == id)
.findFirst().orElse(null);
if(target == null){
target = new Bar();
target.setFooo("");
target.setId(0);
}
return target;
}
But the code above returns an ArrayOutOfBounds Exception and I am not really sure how (since it is a list) or why.
.orElse(null), change toOptional<Bar> target, and useif (bar.isPresent()) return bar.get();, otherwise construct aBar newTarget. --- Even better, use.orElseGet(() -> { Bar newTarget = new Bar(); newTarget.setFooo(""); newTarget.setId(0); return newTarget; })