DEV Community

Jitendra Singh Bisht
Jitendra Singh Bisht

Posted on • Originally published at jsblogs.github.io on

3 1

Optional to stream in java 9

Last year Java 9 launched with tons of new features. In this blog post, I’m going to explain streams in Optional (introduced in Java8). Now you can get streams to form Optional which I think is a good feature.

Below example shows how to get a stream from Optional in Java 8 & Java 9.

package com.jbisht.blogs.java9.usingoptional;

import java.util.Optional;
import java.util.stream.Stream;

public class OptionalDemo {

    public static void main(String[] args) {
        // Java 9 style
        getPerson().stream()
                .map(Person::getName)
                .map("Java 9 "::concat)
                .forEach(System.out::println);

        getEmptyPerson().stream()
                .map(Person::getName)
                .map("Java 9 "::concat)
                .forEach(System.out::println);

        // Java 8 Style
        getPerson()
                .map(Stream::of).orElseGet(Stream::empty)
                .map(Person::getName)
                .map("Java 8 - "::concat)
                .forEach(System.out::println);
    }

    private static Optional<Person> getEmptyPerson() {
        return Optional.empty();
    }

    private static Optional<Person> getPerson() {
        return Optional.of(new Person("JITENDRA SINGH"));
    }

    static class Person {

        private String name;

        public Person(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

Happy Coding 😀😀😀 !!! If you have any feedback please comment down below.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more