简体   繁体   中英

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. 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 . I know I can do this with java like this:

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

but I want do that with 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 . And oh yes, then the string needs to hold a number when it is not 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}

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. 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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