Main Tutorials

Java 8 – Convert Optional<String> to String

In Java 8, we can use .map(Object::toString) to convert an Optional<String> to a String.


  String result = list.stream()
              .filter(x -> x.length() == 1)
              .findFirst()  // returns Optional
              .map(Object::toString)
              .orElse("");

Samples

A standard Optional way to get a value.

Java8Example1.java

package com.mkyong;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Java8Example1 {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("a", "b", "c", "d", "e");

        Optional<String> result = list.stream()
          .filter(x -> x.length() == 1)
          .findFirst();

        if (result.isPresent()) {
            System.out.println(result.get()); // a
        }

    }

}

Output


a

Try map(Object::toString)

Java8Example2.java

package com.mkyong;

import java.util.Arrays;
import java.util.List;

public class Java8Example2 {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("a", "b", "c", "d", "e");

        String s = list.stream().filter(x -> x.length() == 1)
                .findFirst()
                .map(Object::toString)
                .orElse(null);

        System.out.println(s); // a
    }

}

Output


a

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments