0

This is a code snippet that I want to modify.

fullAlert.getSupportingData().forEach( data ->      
    dataMap.put(data.getKey(), data.getValue())
);

I want to check if data.getValue() does return empty or null. If so then

dataMap.put(data.getKey(), data.getValue())

Else I want to replace backslashes

dataMap.put(data.getKey(), data.getValue().replace("\\","\\\\"))

I am new to lambda expressions.

2 Answers 2

1

You probably mean the ternary operator not a lambda expression. That makes sense based on what you ask for.

fullAlert.getSupportingData().forEach(data -> dataMap.put(data.getKey(), data.getValue() != null && !data.getValue().isEmpty()? data.getValue().replace("\\","\\\\") : data.getValue()));
Sign up to request clarification or add additional context in comments.

2 Comments

Lambda is marked by ->. But substitute a simple if by [ternary]() usually has impact on readability. Optional could ease both here: readability and empty/null checks😜
@hc_dev regarding the question however it was more probable that the OP wanted something like that instead of an If/Else statement. Most programmers would not need help to form an if/else statement. Now maybe he could not open the brackets on the body of the lambda function. Only OP knows what needs for real.
0

Are you familiar with if-statements? They work inside lambdas too. You have to open/close a block using curly braces after the arrow:

fullAlert.getSupportingData().forEach( data -> {
    String value = data.getValue(); // default
    if (value != null && !value.isBlank()) {
       value = value.replace("\\","\\\\")); // special
    }
    dataMap.put(data.getKey(), value); // always put into map
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.