Return value when using Java No. 1 Optional.ifPresent that was useful in business

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)

Where it is packed with Optional

I want to receive a list of Optional type and return an OK or error code under certain conditions. You can use if normally, but I received it as Optional, and isPresent seems to be a law, so I was thinking about a good way.

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

Return value when using Java No. 1 Optional.ifPresent that was useful in business
Filter the Java No. 2 Optional list that was useful in business and get the first value
Java No.3 for, stream memory usage useful for business
Differences in code when using the length system in Java
Try Java return value
I was trapped when I generated my own class equals and hashCode in Java using IDE
How to batch initialize arrays in Java that I didn't know when I was a beginner
Note No.5 "HashMap value has multiple values using class" [Java]
Try using RocksDB in Java
Avoid character code error in java when using VScode extension RUN-CODE
How to solve the unknown error when using slf4j in Java