Java 8条件.map()(或具有标识功能的映射) [英] Java 8 conditional .map() (or map with identity function)

查看:244
本文介绍了Java 8条件.map()(或具有标识功能的映射)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有布尔标志来打开/关闭流中的地图。例如修剪与否。

下面的例子是正确的解决方案还是有更好的实现方法?

 布尔值doTrim = true; 
optionalValue.map(doTrim?String :: trim:(x) - > x).get()...

或者:

  boolean doTrim = true; 
optionalValue.map(doTrim?String :: trim:Function.identity()).get()...


解决方案

你过于复杂的事情。如果您有可选< String>您可以简单地说:

  if(doTrim)optionalValue = optionalValue.map(String ::修剪); 

,然后继续操作。调用 get 就可以了。



但是,如果您调用 get()无条件地像你的例子那样,你必须有信心,可选不是, 可选,但是存在。如果您知道字符串存在,您可以更简单:

  String s = optionalValue.get(); 
if(doTrim)s = s.trim();

如果你坚持让所有的代码内联,你当然可以像下面这样写: / p>

 (doTrim?optionalValue:optionalValue.map(String :: trim)).get()

$ b $或b
$ b $ $ p $ (doTrim?optionalValue .get():optionalValue.get()。trim())

但没有真正的优势如果语句在这里超过普通的。如果您有一个真正的可选值,不知道是否存在 String ,并且不想调用 get 立即,我建议我的答案的第一个版本,因为它允许以任何你喜欢的方式继续可选。您在 String :: trim 和身份识别功能之间进行选择的变体可能看起来更时髦,但与传统编程没有什么实质性的优势。


Suppose we have boolean flag to turn on/off map in a stream. For example to trim or not.

Are the below examples proper solution or there is a better way to implement that?

boolean doTrim = true;
optionalValue.map(doTrim ? String::trim : (x) -> x ).get()...

or:

boolean doTrim = true;
optionalValue.map(doTrim ? String::trim : Function.identity() ).get()...

解决方案

You are over-complicating things. If you have an Optional<String> optionalValue you can simply say:

if(doTrim) optionalValue=optionalValue.map(String::trim);

and proceed afterwards, e.g. call get on it.

But if you are calling get() unconditionally as in your example, you have to be confident, that the Optional isn’t, well, optional, but present. If you know that the String is present, you can do it even simpler:

String s=optionalValue.get();
if(doTrim) s=s.trim();

If you insist on having all the code inline, you can, of course, write it like:

(doTrim? optionalValue: optionalValue.map(String::trim)).get()

or

(doTrim? optionalValue.get(): optionalValue.get().trim())

But there is no real advantage over an ordinary if statement here. If you have a real optional value, not knowing whether the String is present, and don’t want to call get immediately, I’d recommend the first version of my answer as it allows to proceed with the Optional in any way you like. Your variant of selecting between String::trim and an identity function may look more funky but has no real advantage over conventional programming.

这篇关于Java 8条件.map()(或具有标识功能的映射)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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