1. Convert Optional String to String – If you are using Java 8 trying to find to convert Convert Optional<String> to String value then you can use below code:
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public class ConvertOptionalToString {
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("JavaHonk1");
stringList.add("JavaHonk2");
stringList.add("JavaHonk3");
stringList.add("JavaHonk4");
Optional<String> value = stringList.stream().findFirst();
String firstValue = value.orElse("");
System.out.println("Optional to String: " +firstValue);
//You can directly usin map to convert String
String mapValue = stringList.stream().findFirst().map(Objects::toString)
.orElse("");
System.out.println("Using map: " + mapValue);
}
}
2. Output:
3. Reference Oracle Java 8