在Java 8中连接两个或多个可选字符串 [英] Concatenate two or more optional string in Java 8

查看:979
本文介绍了在Java 8中连接两个或多个可选字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当简单的问题。在Java 8中,它引入了 Optional 类型。我有两个类型为 Optional< String> 的对象,我想知道连接它们的更优雅方式。

I have a rather simple question for you guys. In Java 8 it was introduced the Optional type. I have two objects of type Optional<String> and I want to know which is the more elegant way to concatenate them.

Optional<String> first = Optional.ofNullable(/* Some string */);
Optional<String> second = Optional.ofNullable(/* Some other string */);
Optional<String> result = /* Some fancy function that concats first and second */;

详细说明,如果其中一个原始可选< String> 对象等于 Optional.empty(),我希望整个连接也是空的。

In detail, if one of the two original Optional<String> objects was equal to Optional.empty(), I want the whole concatenation to be empty too.

请注意,我不是在问如何连接Java中两个 Optional 的评估,而是如何连接两个 String s里面有一些可选

Please, note that I am not asking how to concatenate the evaluation of two Optionals in Java, but how to concatenate two Strings that are inside some Optional.

提前致谢。

推荐答案

我找到的解决方案如下:

The solution I found is the following:

first.flatMap(s -> second.map(s1 -> s + s1));

可以使用专用方法清理,如下所示:

which can be cleaned using a dedicated method, such the following:

first.flatMap(this::concat);
Optional<String> concat(String s) {
    second.map(s1 -> s + s1);
}

但是,我认为可以找到更好的东西。

However, I think that something better can be found.

如果我们想要推广到 Optional< String> 的列表或数组,那么我们可以使用类似于以下内容的东西。

If we want to generalize to a list or an array of Optional<String>, then we can use something similar to the following.

Optional<String> result =
    Stream.of(Optional.of("value1"), Optional.<String>empty())
          .reduce(Optional.of(""), this::concat);

// Where the following method id used
Optional<String> concat(Optional<String> first, Optional<String> second) {
    return first.flatMap(s -> second.map(s1 -> s + s1));
}

请注意,为了编译上面的代码,我们必须手动绑定类型变量 Optional.empty() to String

Note that in order to compile the above code, we have to manually bind the type variable of Optional.empty() to String.

这篇关于在Java 8中连接两个或多个可选字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆