简体   繁体   English

Java 8 可选将字符串解析为 int 或如果是 null 并设置默认空字符串

[英]Java 8 Optional parse string to int or if is null and set default empty string

I'm trying to parse string to int and set as default an empty string if the string is null with lambda.如果字符串是null和 lambda,我正在尝试将string解析为int并将默认设置为空string Here is my code:这是我的代码:

Map<String, Object> myMap = new HashMap<>();
String myString = "Some String"; //can be also null

myMap.put("myData", Optional.ofNullable(myString).map(Integer::parseInt).orElse(""));
...

The Problem is that i should to set an Integer in .orElse() as default but I need to set and empty string .问题是我应该在.orElse()中设置一个Integer作为默认值,但我需要设置和空string I know I can do this with java like this:我知道我可以像这样使用 java 做到这一点:

myMap.put("myData", StringUtils.isEmpty(myString) ? "" : Integer.parseInt(myString));

but I want do that with lambda.但我想用 lambda 做到这一点。

Can someone help me with that?有人可以帮我吗?

It's fairly straightforward.这很简单。 We just need to tell the stream pipeline to consider the Integer an Object , not an Integer .我们只需要告诉 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 管道考虑Integer一个Object ,而不是一个Integer And oh yes, then the string needs to hold a number when it is not null.哦,是的,那么当它不是 null 时,字符串需要保存一个数字。

    Map<String, Object> myMap = new HashMap<>();
    String myString = "53"; //can be also null

    myMap.put("myData",
            Optional.ofNullable(myString)
                    .map(s -> (Object) Integer.valueOf(s))
                    .orElse(""));
    
    System.out.println(myMap);

This outputs:这输出:

{myData=53} {我的数据=53}

And if I change this line:如果我改变这一行:

    String myString = null; //can be also non-null

{myData=} {我的数据=}

You do not need to use an Optional , and some would prefer that you don't.您不需要使用Optional ,有些人希望您不要。 Here's a variant without it:这是一个没有它的变体:

    myMap.put("myData", myString == null ? "" : Integer.valueOf(myString));

The result is the same as before.结果和以前一样。 Do you agree that it's simpler?你同意它更简单吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM