简体   繁体   中英

How to extract only the first word from a Java Optional String using a delimiter

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?

You don't need to generate a Stream.

Instead, you can make use of the String.replaceFirst() , which expects a regular expression and a replacing String, like that replaceFirst("@.*", "") , which will remove everything after an at sign @ (including @ itself).

email.ifPresent(
    s -> myBuilder.set(
        UserName,
        s.replaceFirst("@.*", ""))
    );

By the way, since you've specified email variable with private access modifier, obviously it's a field. Hence, it is worth to point out that having field of Optional type isn't very beneficial. The common practice is to unpack the optional before instantiating the object, rather than storing a potentially empty optional (for instance, in some cases it might make no sense to create a new domain object if the optional doesn't contain data, eg : user without email can not exist).

You might be interested in reading these Questions:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM