Skip to content
Advertisement

Get rid of Optional [] String? [closed]

Testing with streams on Stackoverflow API in Java

    public Optional<String> getShortestTitel() {
    // return the the shortest title
    return stream().map(Question::getTitle).min(Comparator.comparingInt(String::length));
}

my Output:

Optional[Check instanceof in stream]

how can I get rid of the Optional[]?

Advertisement

Answer

You can use Optional#orElseGet e.g.

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

class Question {
    private String title;

    public Question(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }
}

public class Main {
    public static void main(String[] args) {
        // Test
        Question q1 = new Question("Hello");
        Question q2 = new Question("World");
        System.out.println(getShortestTitel(List.of(q1, q2)).orElseGet(() -> ""));
    }

    public static Optional<String> getShortestTitel(List<Question> list) {
        // return the the shortest title
        return list.stream().map(Question::getTitle).min(Comparator.comparingInt(String::length));
    }
}

Output:

Hello
Advertisement