I got this Optional String (non-null) for which I want to extract only the first word (in this case – username, out of an email address). What is the best way to do it with Optional, given the fact I can disregard everything after the delimiter ('@', in this case). I do not want a stream as a result, just a single string.
@NonNull private final Optional<String> email;
email.ifPresent(s -> myBuilder.set(UserName, s));
So an input for example: hello@domain.com
Desired results: hello
Tried in many ways but theres always some sort of limitation with this Optional string & streams. I am new to it so I'm sure there's something I don't understand properly.
Optional<String> userName = Stream.of(email)
.filter(Optional::isPresent)
.map(Optional::get)
.<What's next?>
Or
if (email.isPresent()) {
Optional <String> userName = Pattern.compile("@").splitAsStream(email).toString();
}
Doesn't compile but I know it is wrong.
edit:
I looked up trim @domain.xxx from email leaving just username but it doesn't help me because this is not a regular string but Optional & streams. Also, I do not want to get an array of results but a single result
edit2:
if (email.isPresent()) {
Optional<String> newAccountName = Arrays.stream(email.get().split("@")).findFirst();
}
Is this the right way to go?