Reputation: 3284
Pretty new to Optional/Java8 usage and I had a doubt regarding its usage. I have a function in my API which returns a String which can be null or empty. Its similar to finding the id in email like: [email protected] -> abc is o/p.
Now one way of doing this was:
public Optional<String> getUser(final String emailId) {
if (TextUtils.isEmpty(emailId)) {
return Optional.empty();
}
String userIDSeparator = "@";
int userNameEndIndex = emailId.indexOf(userIDSeparator);
if (userNameEndIndex == -1) {
return Optional.empty();
}
return Optional.of(emailId.substring(0, userNameEndIndex));
}
I was wondering if there is any neater way of doing this to return an Optional?
Also, Optional was introduced in Java8 so is there anyway the code can be java7 compatible? I am aware of preprocessors in C not sure if something similar is available.
Note: I have not compiled this code, so there might be some errors. I wanted the input on Optional.
Thanks!
Upvotes: 6
Views: 20747
Reputation: 56423
Well, the code can certainly be reduced. i.e.
public Optional<String> getUser(final String emailId) {
return Optional.of(emailId)
.filter(email -> email.contains("@"))
.map(email -> email.substring(0, email.indexOf("@")));
}
if this method can ever receive a null
value then you'd need to change Optional.of(emailId)
to Optional.ofNullable(emailId)
.
As for:
Also, Optional was introduced in Java8 so is there any way the code can be java7 compatible?
Not that I know of. There may be other libraries that have similar functionality to Java's Optional type, so a little bit of research online may get you to the right place.
Upvotes: 6
Reputation: 59960
Maybe you mean something like this :
public Optional<String> getUser(final String emailId) {
return Optional.ofNullable(emailId)
.filter(email -> email.contains("@"))
.map(email -> Optional.of(email.replaceAll("(.*?)@.*", "$1")))
.orElseGet(Optional::empty);
}
Example
null -> Optional.empty
"" -> Optional.empty
"[email protected]" -> abd
As @Aominè mention, there are some unnecessary parts in my solution, you can use this version instead :
public Optional<String> getUser(final String emailId) {
return Optional.ofNullable(emailId)
.filter(email -> email.contains("@"))
.map(email -> email.replaceAll("(.*?)@.*", "$1"));
}
Upvotes: 5