Posts

Showing posts with the label How to Convert Optional<String> to String

How to Convert Optional to String in Java 8

In this section, we will show you h ow 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" ,