下面的方法返回一个Map.我正在添加一个跳过DAO如何返回值映射的伪代码.
public Map<Intger,Integer> getIDsBasingonRanks(){
Map<Integer,Integer> m = new HashMap<>();
// Dao operation fetcing values from DB;
if(dao==null){
//logging some error or info
return null;// In this cases Null Pointer will be thrown. How to handle it ?
}
m.put()// put the values inside the map from DAO
return m;
}
Run Code Online (Sandbox Code Playgroud)
现在我getIDsBasingonRanks()
从另一个返回Map的类调用并从此映射中获取值
Map<Integer,Integer> m2 = getIDsBasingonRanks();
m2.getkey();//Incase the map is null we will have Null Pointer Exception
m2.getValue(); //Incase the map is null we will have Null Pointer Exception
Run Code Online (Sandbox Code Playgroud)
在dao = null条件下处理上述方法的return语句我感觉很棘手.当返回null时如何提供返回方法以克服空指针,因为我们也无法处理它们.
一种可能性是可选的.
public Optional<Map<Integer, Integer>> getIDsBasingonRanks() {
Map<Integer, Integer> m = new HashMap<>();
... // Dao operation fetcing values from DB;
if (dao == null) {
return Optional.empty();
}
... // put the values inside the map from DAO
return Optional.of(m);
}
getIDsBasingonRanks().ifPresent(m ->
{
... m.get(42) ...
});
int y = getIDsBasingonRanks().map(m -> m.get(42)).orElse(13);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
592 次 |
最近记录: |