2

This code should return the Optional String when given siteUrl contains key from the predefined list of pairs (or Optional.empty() otherwise).

Is there a better way than using new Pair(null, null) here? Or maybe change the whole expression?

static Optional<String> get(String siteUrl) {
    return Optional.ofNullable(URL_TO_ENVIRONMENT
            .stream()
            .filter(p -> siteUrl.contains(p.getKey()))
            .findFirst().orElse(new Pair(null, null)).getValue());
}

private static final List<Pair> URL_TO_ENVIRONMENT = buildList();

private static List<Pair> buildList() {
    return Arrays.asList(
            new Pair("aaa.mysite.com", "aaa_something"),
            new Pair("bbb.mysite.com", "bbb_something"),
            new Pair("ccc.mysite.com", "ccc_comething"));
}

1 Answer 1

5
return URL_TO_ENVIRONMENT.stream()
    .filter(p->siteUrl.contains(p.getKey()))
    .map(Pair::getvalue)
    .findFirst();

Do you specifically need the first match? if you just want any match, use findAny instead of findFirst.

Sign up to request clarification or add additional context in comments.

6 Comments

wow, this was fast. I actually just need "any match". thank you, Misha!
I'd prefer URL_TO_ENVIRONMENT.stream().filter(p->siteUrl.contains(p.getKey())).findAny().map(Pair::getvalue);. This way mapping is done outside of the pipeline keeping the pipeline shorter (less stack depth, more chances for inlining, etc.).
@TagirValeev In my observation, stream-like operations on Optional (map, filter, flatMap) tend to throw people off. So I have a (very) slight preference to avoid them.
@Tagir Valeev: the total stack depth doesn’t matter as the hotspot still spans the same deep-most stack frames.
@Holger: sometimes it does matter as it can hit the MaxInlineLevel limit, so you will have something not inlined which would be inlined otherwise. Will try to make some sample benchmark later...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.