Simplifying the If-Else Condition Using Java Functional Style Programming

Simplifying the if-else condition using Java Functional Style Programming

If you don't want to count zeros, you code is as simple as it can get. If you wanted to count zeros as positive, however then you could shorten it to this.

int[] ans = new int[2];
for (int i : list) ans[i < 0 ? 1 : 0] += 1;

How to simplify multiple ifs statements with lambda

How would lambdas help at all?

@Value
public static class MessageAccountKey {
// this class needs a better name;
// you'd know better what it represents
String messageType, accountType;
}

private static final Map<MessageAccountKey, Integer> MAP = Map.of(
new MessageAccountKey("PDF", "NEXT"), 2015,
new MessageAccountKey("CSV", "NEXT"), 2016,
new MessageAccountKey("CSV", "BEFORE"), 2017,
new MessageAccountKey("PDF", "BEFORE"), 2018);

private static int resolveType(String messageType, String accountType) {
// consider changing to a single arg of type Key.
return MAP.getOrDefault(new MessageAccountKey(messageType, accountType), 0);
}

The 'key' class needs functional equals and hashCode impls, here done with lombok's @Value.

The MAP can also be built up from an input text file (use getResourceAsStream and a static initializer if you prefer.

Simplifying Conditional Operators

Your only option for a one-liner is to use parenthesis. Personally, I prefer multiple statements to make things much clearer:

boolean isXInRange = x > 0 && x < 1;
boolean isYInRange = y > 0 && y < 1;
boolean truth = isXInRange && isYInRange;

How to write an If-Else loop involving multiple conditions in an idiomatic Scala way?

First off, we like to avoid nulls by nipping them off as early as possible.

val o1 = Option(/*code that retrieved/created c1*/)
val o2 = Option(/*code that retrieved/created c2*/)

Then code that "manipulates" mutable variables is a bad idea, but as you didn't include that part we can't offer better solutions for it.

val flag = o1.fold(o2.nonEmpty)(_ => o2.isEmpty) &&
//other code continues that calculates flag value


Related Topics



Leave a reply



Submit