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

43 Views Asked by At

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

There are 1 best solutions below

0
Federico klez Culloca On BEST ANSWER

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"