Null checking is a problem many times when writing Java in business. But it is troublesome to check with StringUtil and CollectionUtil one by one. I don't know if null will be returned in the interface created by humans in the first place. There is something like that. .. ..
I want to write it smoothly and coolly, but I couldn't understand the behavior, so I'll share it.
(Maybe I'm just lacking in my ability)
I want to receive a list of Optional
The first thing I thought about
testList.ifPresent(c ->{
c.forEach(t -> {
if(t=="hoge") {
return "OK";
}
});
});
Compile error Because ifPresent and forEach are both Consumer type? Because it can only consume the value. It cannot return a return value.
I thought about
List<String> test(Optional<List<String>> testList){
List<String> selectedList = new ArrayList<>();
testList.ifPresent(c ->{
c.forEach(t -> {
if(t=="hoge") {
selectedList.add("Ok");
}
});
});
return selectedList;
}
Now you can return a list of strings. If the return value is String, you can get the string by getting (0). But, needless to say, it's shit because I'm making an unnecessary array.
It was good that I used to return List this time, but if I have to return the return value as String, it seems better to use if obediently.
Please let me know if there is a good way to return a singular return value while using ifPresent.
Null check is annoying If there is a possibility of null by convention, I want you to return everything with Optinal ...
Recommended Posts