Oliver
Oliver

Reputation: 4173

How to turn a optional of an string array into a optional of a string?

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");

Upvotes: 1

Views: 62

Answers (1)

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

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"

Upvotes: 6

Related Questions