How to Convert Optional to String in Java 8
In this section, we will show you how to convert Optional<String> to String.
Samples
A standard way to get a value.
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "i", "h", "d", "e");
Optional<String> result = list.stream()
.filter(x -> x.length() == 1)
.findFirst();
if (result.isPresent()) {
System.out.println(result.get()); // a
}
}
}
Console Output:
a
use .map(Object::toString) to convert an Optional<String> to a String.
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "i", "h", "d", "e");
String s = list.stream().filter(x -> x.length() == 1)
.findFirst()
.map(Object::toString)
.orElse(null);
System.out.println(s); // a
}
}
Console Output:
a
More...