I want to replace conventional if else with lambda. Consider following highlighted code, is there some simple way to have this represented with Lambda ?
public class IfElseLambda {
public static void main(String[] args) {
String value = null;
DataObj data = new DataObj();
List<DataObj> dataObjs = data.getDataObjs();
***if (dataObjs != null) {
value = dataObjs.stream().map(dataObject -> getValue(dataObject)).filter(Objects::nonNull).findFirst().orElse(null);
} else {
value = getValue(data);
}***
}
public static String getValue(DataObj dataObj) {
return "Get value from dataObj";
}
}
class DataObj {
List<DataObj> dataObjs;
public List<DataObj> getDataObjs() {
return dataObjs;
}
public void setDataObjs(List<DataObj> dataObjs) {
this.dataObjs = dataObjs;
}
}
lambdais a function andif-elseis..if-elsehow do you want to replace a condition with a function?if-elsewith lambda. If it's because you don't likeif-else, use a? :ternary operator.if-elseis a basic, well-known construct. Why would you want to overengineer it into a lambda?if-else, which means e.g.value = (dataObjs == null ? getValue(data) : dataObjs.stream()...findFirst().orElse(null));--- See, noif-else.