rewrite if else null check using optionals - java-8

Is there a way to rewrite this using Optional and lambdas in a more succinct and clear way?
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
if(avgBuySellPriceTerm == null){
return false;
}else{
if(avgBuySellPriceTerm.getIndicator()!= null && ! avgBuySellPriceTerm.getIndicator().isEmpty()){
return true;
}else{
return false;
}
}
}

Here's a suggestion with Optional:
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
return Optional.ofNullable(avgBuySellPriceTerm)
.map(AvgBuySellPriceTerm::getIndicator)
.map(i -> !i.isEmpty()) // return true if getIndicator
// is not empty
.orElse(false);
}

The following should do it, using an Optional::ofNullable and the classic map, filter and isPresent methods
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
return Optional.ofNullable(avgBuySellPriceTerm)
.map(AvgBuySellPriceTerm::getIndicator)
.filter(ind -> !ind.isEmpty())
.isPresent();
}

!Optional.ofNullable(t)
.map(AvgBuySellPriceTerm::getIndicator)
.map(List::isEmpty)
.orElse(true);
Not sure this is more readable though.

Again, not using lambdas here but keeping it readable. The first if statement can be omitted, so it can all boil down to:
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
if(avgBuySellPriceTerm != null && avgBuySellPriceTerm.getIndicator()!= null && !avgBuySellPriceTerm.getIndicator().isEmpty()){
return true;
}
return false;
}

Related

Spring is converting String values to false for #queryparam Boolean

I have this as queryparam in my requestmapping:
#QueryParam("isBenchmark") boolean isBenchmark
Now if am passing any String value also it is defaulting it to false. How can I avoid this and throw error if it is anything other than true/false.
Is there any annotations with which I can throw such validations
It is a known issue.
It is converted to boolean using the new Boolean(isBenchmark) So when isBenchmark is true it converts to true, in all other cases it converts to false.
Unfortunately you have to handle it by your self
public void YourMethod(#QueryParam("isBenchmark") String isBenchmark) {
boolean val
if (isBenchmark != null && isBenchmark.equals("true")){
val = true;
} else if (isBenchmark != null && isBenchmark.equals("false")) {
val = false;
} else {
Throw Exception or return a bad request
}
}

map has list as value check if null

I have a Map in Java 8.
I need to check if the list that comprises the map value is empty or null and return the result .
I have tried likewise with no luck
public boolean mapValuesEmpty() {
boolean result = true;
for (Entry<Integer, List<SomeObjectName>> entry : eventLogsMap.entrySet()) {
if (entry.getValue() != null) {
result = false;
break;
}
}
return result;
}
Many thanks
boolean result = eventLogsMap
.values()
.stream()
.anyMatch(list -> list != null && !list.isEmpty())

How to reduce the if-else depth?

I have this example code
public static ActionProcessable getActionProcessor(TaskType currentTaskType, UserAction userAction){
String actionKey;
if(userAction != null){
if(currentTaskType != null){
actionKey = buildKey(currentTaskType, userAction);
if(dossierActions.containsKey(actionKey)){
return dossierActions.get(actionKey);
}
}
actionKey = buildKey(anyTaskType(), userAction);
if(dossierActions.containsKey(actionKey)){
return dossierActions.get(actionKey);
}
}
return new NullActionProcessor();
}
In this logic i have a map to store the ActionProcessable by combined-key TaskType and UserAction. This method will return ActionProcessable with input taskType and action. TaskType can be null so in that case we only need to get by userAction.
When i check this code by sonar, it say the third if is "Nested if-else depth is 2 (max allowed is 1)"
But i don't know how to make it better.
Does anyone suggest me something?
You can move "if containsKey" part out of condition to remove code duplication:
public static ActionProcessable getActionProcessor(TaskType currentTaskType, UserAction userAction){
if (userAction != null) {
String actionKey = currentTaskType != null
? buildKey(currentTaskType, userAction)
: buildKey(anyTaskType(), userAction);
if (dossierActions.containsKey(actionKey)){
return dossierActions.get(actionKey);
}
}
return new NullActionProcessor();
}
Now, intent of the code looks more clear (at least, for me).
You can also make the first condition short-circuit and\or use ternary if for containsKey, it will remove even more ifs, but can make code more complex for some people.
public static ActionProcessable getActionProcessor(TaskType currentTaskType, UserAction userAction){
if (userAction == null) {
return new NullActionProcessor();
}
String actionKey = currentTaskType != null
? buildKey(currentTaskType, userAction)
: buildKey(anyTaskType(), userAction);
return dossierActions.containsKey(actionKey)
? dossierActions.get(actionKey);
: new NullActionProcessor();
}
Choose the one you like, they are technically similar.
Since you haven't specified specific programming language, one more thing to say: your code is a good example of use case of null-coalsecing operator. Sadly, AFAIK, there is none in Java. In C#, the code could look like this:
public static ActionProcessable GetActionProcessor(TaskType currentTaskType, UserAction userAction) {
if (userAction == null) {
return new NullActionProcessor();
}
var actionKey = BuildKey(currentTaskType ?? anyTaskType(), userAction);
return dossierActions[actionKey] ?? new NullActionProcessor();
}

Java 8 Stream, anyMatch

boolean isSuccess = aMap.entrySet().stream().anyMatch(entry -> {
AKey aKey= entry.getKey();
BValue bValue = bMap.get(aKey);
if (bValue == null) {
return false;
}
AValue aValue = entry.getValue();
if (compareDetail(aValue, bValue)) {
return false;
}
return true;
}
);
this code always only loop one time, how can i loop all elements then return true when two if blocks false?
It seems you need to try allMatch instead.

Boolean Method for ArrayList

I have created an ArrayList and I am looking to use a boolean method to add an element to the ArrayList.
private static Arraylist <Bicycle> bikelist = new Arraylist<Bicycle>();
public boolean add(Bicycle bicycle)
{
if( bikelist.size() != -1)
return true;
bikelist.add(bicycle);
}
return false;
Would this be plausible? I'm not quite sure how boolean methods work? Do they have to contain an if statement to return true or false?
Using: public boolean add(Object obj): Adds an element obj to the Arraylist. If the element is added successfully, this method returns true
Depends on what you want to return the boolean value for.
For whether the add operation succeeded: the only reason why adding an Object to an ArrayList would fail is due to an OutOfMemoryException AFAIK. Then you would do:
public boolean add(Object obj) {
try {
list.add(obj);
} catch (OutOfMemoryException e) {
return false;
}
return true;
}
If you want to return false if the list already contains the object, then:
public boolean add(Object obj) {
if (list.contains(obj)) {
return false;
}
list.add(obj);
return true;
}
Note that ArrayList<T>.contains(T) checks for object equality using Object.equals(Object). Thus you need to override equals() for your custom class.
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Bicycle other = (Bicycle) obj;
if (other.owner != this.owner) {
return false;
}
if (this.model != other.model) {
return false;
}
return true;
}

Resources