|
1 | | -# <img src="https://raw.githubusercontent.com/bobocode-projects/resources/master/image/logo_transparent_background.png" height=50/>Lambda Functions Map |
2 | | -Start learning functional programming in Java by writing simple math functions using Lambdas 💪 |
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.Map; |
| 3 | +import java.util.function.IntUnaryOperator; |
3 | 4 |
|
4 | | -### Objectives |
| 5 | +public class LambdaFunctionsMap { |
5 | 6 |
|
6 | | -* implement **abs** (absolute) function using lambda ✅ |
7 | | -* implement **sgn** (signum) function using lambda ✅ |
8 | | -* implement **increment** function using lambda ✅ |
9 | | -* implement **decrement** function using lambda ✅ |
10 | | -* implement **square** function using lambda ✅ |
11 | | -* add all those functions to the function map ✅ |
| 7 | + private final Map<String, IntUnaryOperator> functionMap = new HashMap<>(); |
12 | 8 |
|
13 | | ---- |
| 9 | + public LambdaFunctionsMap() { |
| 10 | + |
| 11 | + IntUnaryOperator abs = x -> x >= 0 ? x : -x; |
14 | 12 |
|
15 | | -#### 🆕 First time here? – [See Introduction](https://github.com/bobocode-projects/java-fundamentals-exercises/tree/main/0-0-intro#introduction) |
| 13 | + |
| 14 | + IntUnaryOperator sgn = x -> x > 0 ? 1 : (x < 0 ? -1 : 0); |
16 | 15 |
|
17 | | -## |
18 | | -<div align="center"><img src="https://raw.githubusercontent.com/bobocode-projects/resources/master/animation/GitHub%20Star_3.gif" height=50/></div> |
| 16 | + |
| 17 | + IntUnaryOperator increment = x -> x + 1; |
| 18 | + |
| 19 | + |
| 20 | + IntUnaryOperator decrement = x -> x - 1; |
| 21 | + |
| 22 | + |
| 23 | + IntUnaryOperator square = x -> x * x; |
| 24 | + |
| 25 | + |
| 26 | + functionMap.put("abs", abs); |
| 27 | + functionMap.put("sgn", sgn); |
| 28 | + functionMap.put("increment", increment); |
| 29 | + functionMap.put("decrement", decrement); |
| 30 | + functionMap.put("square", square); |
| 31 | + } |
| 32 | + |
| 33 | + |
| 34 | + public Map<String, IntUnaryOperator> getFunctionMap() { |
| 35 | + return functionMap; |
| 36 | + } |
| 37 | + |
| 38 | + |
| 39 | + public static void main(String[] args) { |
| 40 | + LambdaFunctionsMap lfm = new LambdaFunctionsMap(); |
| 41 | + |
| 42 | + System.out.println("abs(-5) = " + lfm.getFunctionMap().get("abs").applyAsInt(-5)); |
| 43 | + System.out.println("sgn(-5) = " + lfm.getFunctionMap().get("sgn").applyAsInt(-5)); |
| 44 | + System.out.println("increment(7) = " + lfm.getFunctionMap().get("increment").applyAsInt(7)); |
| 45 | + System.out.println("decrement(7) = " + lfm.getFunctionMap().get("decrement").applyAsInt(7)); |
| 46 | + System.out.println("square(4) = " + lfm.getFunctionMap().get("square").applyAsInt(4)); |
| 47 | + } |
| 48 | +} |
0 commit comments