5
I would like to build a method using Java 8, replacing the conditional IF, ELSE-IF and ELSE. For this, I built a sequence of code, I do not know if it is ideal and would like to hear better opinions or solutions.
public static void main(String[] args) {
String a = " A ";
String b = " B ";
String c = " C ";
String d = null;
String teste = Optional.ofNullable(d)
.map(String::trim)
.orElseGet(() -> Optional.ofNullable(a)
.map(String::trim)
.orElseGet(() -> Optional.ofNullable(b)
.map(String::trim)
.orElseGet(() -> Optional.ofNullable(c)
.map(String::trim)
.orElse(""))));
System.out.println(teste);
}
For didactic purposes, I used Strings as examples, BUT what if for example we had the following case: use a method "private String returns Search(String regex)". If regex finds something, it returns the String. If it returns NULL, I call the method again with another regex. And so on until the regex are finished and return by default the empty value ("")
Following example:
public static void main(String[] args) {
String regexA = "A";
String regexB = "B";
String regexC = "C";
Pattern patternA = Pattern.compile(regexA);
Pattern patternB = Pattern.compile(regexB);
Pattern patternC = Pattern.compile(regexC);
String valor = " C ";
String teste = Optional.ofNullable(valor)
.map(str -> retornaBusca(str, patternA))
.orElseGet(() -> Optional.ofNullable(valor)
.map(str -> retornaBusca(str, patternB))
.orElseGet(() -> Optional.ofNullable(valor)
.map(str -> retornaBusca(str, patternC))
.orElse("")));
System.out.println(teste);
}
private static String retornaBusca(String str, Pattern regex) {
return Optional.ofNullable(str)
.map(regex::matcher)
.filter(Matcher::find)
.map(Matcher::group)
.map(String::trim)
.orElse(null);
}
The result of this System.out.println(test) will be that string?
– MauroAlmeida
Yes. Since d is null, it takes the value of a. If a is null, it takes the value of b. And so on. If it hits C and it’s null, it’s empty anyway. But the idea would be to replace the Strings with methods that return Strings if found from a regex or null if they do not find.
– Gustavo
I edited my answer.
– Victor Stafusa