1

I struggle with finding an elegant way to convert a variable of type Optional<String[]> to Optional<String> and joining all elements of the given array.

Is there an elegant solution for this?

Optional<String[]> given = Optional.ofNullable(new String[]{"a", "b"});

Optional<String> joinedString = ....;

Assertions.assertThat(joinedString.get()).isEqualTo("ab");

1 Answer 1

6

Looks to me like a simple map operation with String.join().

Optional<String[]> given = Optional.ofNullable(new String[]{"a", "b"});
var joinedString = given.map(s -> String.join("", s));
System.out.println(joinedString.get()); // prints "ab"
Sign up to request clarification or add additional context in comments.

Comments

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.