Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 去掉可选的[]字符串?_Java - Fatal编程技术网

Java 去掉可选的[]字符串?

Java 去掉可选的[]字符串?,java,Java,在Java中的Stackoverflow API上使用streams进行测试 public Optional<String> getShortestTitel() { // return the the shortest title return stream().map(Question::getTitle).min(Comparator.comparingInt(String::length)); } public可选getshortestitel(){

在Java中的Stackoverflow API上使用streams进行测试

    public Optional<String> getShortestTitel() {
    // return the the shortest title
    return stream().map(Question::getTitle).min(Comparator.comparingInt(String::length));
}
public可选getshortestitel(){
//返回最短的标题
返回stream().map(Question::getTitle).min(Comparator.comparingInt(String::length));
}
我的输出:

可选[检查流中的实例]

如何摆脱可选的[]?

您可以使用例如


您如何打印此输出?请也给我们看一下代码。提供了各种方法来实现这一点。祝你好运。为什么不
可选#orElse
?@iota-这取决于需求<如果需要静态值,则可以使用代码>可选#或LSE。使用
可选的#orElseGet
,可以动态生成任何值。@ArvindKumarAvinash:.orElseGet(()->“”)。。。分配和调用lambda是有代价的。您的意思是,即使在值简单且计算成本较低的情况下(如空字符串),使用lambda表达式也有意义吗?@scottb-您的意思是,即使在值简单且计算成本较低的情况下(如空字符串),使用lambda表达式也有意义吗?-不,我说过这取决于要求。
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));
    }
}
Hello