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...

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete