Skip to content

Instantly share code, notes, and snippets.

@staypufd
Last active December 14, 2024 05:09
Show Gist options
  • Save staypufd/d16737d31117a041295fed7ff2168f4f to your computer and use it in GitHub Desktop.
Save staypufd/d16737d31117a041295fed7ff2168f4f to your computer and use it in GitHub Desktop.
Enums for the win...
// Gist inspired by comment to:
//
// https://medium.com/javarevisited/re-write-this-java-if-else-code-block-or-ill-reject-your-pull-request-953f20c0f544
import java.util.ArrayList;
import java.util.List;
class Scratch {
// Sample ops and input data for demo below
static List<Operation> ops = List.of(Operation.MULTIPLY, Operation.PLUS);
static List<Integer> xNums = List.of(1, 22);
static List<Integer> yNums = List.of(5, 4);
public static void main(String[] args) {
// Enum exmaple
System.out.println(Operation.PLUS.perform(4, 9));
// Accumulator for
var resList = new ArrayList();
for ( int i = 0; i < ops.size(); i++) {
final int finalI = i;
// Java streams can't stream over multiple collections (3 in this case) at the same time, unless Gathers can do that now...
// so we iterate or the outer accumulator, and map for the enum operation.
resList.add(ops.stream().map(operation -> (operation.perform(xNums.get(finalI), yNums.get(finalI)))).toList());
};
System.out.println(resList);
}
public enum Operation {
PLUS,
MINUS,
MULTIPLY,
DIVIDE;
public int perform(int x, int y) {
switch (this) {
case PLUS:
return x + y;
case MINUS:
return x - y;
case MULTIPLY:
return x * y;
case DIVIDE:
return x / y;
default:
throw new RuntimeException("Bad Operator");
}
}
}
}
@staypufd
Copy link
Author

When run you get this output:

13
[[5, 6], [88, 26]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment