Merge branch 'master' into BAEL-5197/new_features_in_javav17

This commit is contained in:
Thiago dos Santos Hora
2021-11-06 12:19:15 +01:00
committed by GitHub
284 changed files with 3627 additions and 1081 deletions

View File

@@ -0,0 +1,25 @@
package com.baeldung.switchpatterns;
public class GuardedPatterns {
static double getDoubleValueUsingIf(Object o) {
return switch (o) {
case String s -> {
if (s.length() > 0) {
yield Double.parseDouble(s);
} else {
yield 0d;
}
}
default -> 0d;
};
}
static double getDoubleValueUsingGuardedPatterns(Object o) {
return switch (o) {
case String s && s.length() > 0 -> Double.parseDouble(s);
default -> 0d;
};
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.switchpatterns;
public class HandlingNullValues {
static double getDoubleUsingSwitchNullCase(Object o) {
return switch (o) {
case String s -> Double.parseDouble(s);
case null -> 0d;
default -> 0d;
};
}
static double getDoubleUsingSwitchTotalType(Object o) {
return switch (o) {
case String s -> Double.parseDouble(s);
case Object ob -> 0d;
};
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.switchpatterns;
public class ParenthesizedPatterns {
static double getDoubleValueUsingIf(Object o) {
return switch (o) {
case String s -> {
if (s.length() > 0) {
if (s.contains("#") || s.contains("@")) {
yield 0d;
} else {
yield Double.parseDouble(s);
}
} else {
yield 0d;
}
}
default -> 0d;
};
}
static double getDoubleValueUsingParenthesizedPatterns(Object o) {
return switch (o) {
case String s && s.length() > 0 && !(s.contains("#") || s.contains("@")) -> Double.parseDouble(s);
default -> 0d;
};
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.switchpatterns;
public class PatternMatching {
public static void main(String[] args) {
Object o = args[0];
if (o instanceof String s) {
System.out.printf("Object is a string %s", s);
} else if(o instanceof Number n) {
System.out.printf("Object is a number %n", n);
}
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.switchpatterns;
public class SwitchStatement {
public static void main(String[] args) {
final String b = "B";
switch (args[0]) {
case "A" -> System.out.println("Parameter is A");
case b -> System.out.println("Parameter is b");
default -> System.out.println("Parameter is unknown");
};
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.switchpatterns;
public class TypePatterns {
static double getDoubleUsingIf(Object o) {
double result;
if (o instanceof Integer) {
result = ((Integer) o).doubleValue();
} else if (o instanceof Float) {
result = ((Float) o).doubleValue();
} else if (o instanceof String) {
result = Double.parseDouble(((String) o));
} else {
result = 0d;
}
return result;
}
static double getDoubleUsingSwitch(Object o) {
return switch (o) {
case Integer i -> i.doubleValue();
case Float f -> f.doubleValue();
case String s -> Double.parseDouble(s);
default -> 0d;
};
}
}