[英]How to compare maps and store the result into Value Objects using Java?
我正在嘗試處理3個哈希表並將其數據放入值對象列表。 但是,我的代碼在某處出現問題。
這是我要完成的任務的方案:
Map1是源地圖,map2和map3用於與map1比較。 最后,我將結果存儲到VO(值對象)中。
HashMap<Integer, BigDecimal> map1=new HashMap<Integer, BigDecimal>();
map1.put(1,10)
map1.put(2,20)
map1.put(3,30)
map1.put(4,40)
map1.put(5,50)
Map<Integer,String> map2=new HashMap<Integer,String>();
map2.put(1,"Y");
map2.put(2,"N");
Map<Integer,String> map3=new HashMap<Integer,String>();
map3.put(3,"N");
map3.put(4,"N");
map3.put(5,"N");
public Map<Integer, BigDecimal> process(
final Map<Integer, BigDecimal> map1,
final Map<Integer, String> map, final List<EmployeeVO> empDetails) {
final Iterator<Integer> keys = map1.keySet().iterator();
while (keys.hasNext()) {
final EmployeeVO empVO = new EmployeeVO();
final Integer empKeys = keys.next();
empVO.setEmpId(empKeys);
empVO.setEmpAmount(map1.get(empKeys));
if (("Y".equals(map.get(empKeys)))) {
empVO.setInd("Y");
keys.remove();
} else
empVO.setInd("N");
empDetails.add(empVO);
}
return map1;
}
員工VO:
public class EmployeeVO{
private BigDecimal empAmount=new BigDecimal(0);
private Integer empId;
private String ind;
//setters and getters
}
我正在像下面這樣調用上面的方法,令人驚訝的是我正在將10條記錄放入我的列表對象。
final List<EmployeeVO> empDetails = new CopyOnWriteArrayList<EmployeeVO>();
final Map<Integer, BigDecimal> result1 = process(map1, map2, empDetails );
final Map<Integer, BigDecimal> result2 = process(map1, map3, empDetails );
預期結果:列表應包含5個VO對象,但有9條記錄
我認為問題出在這里:
if (("Y".equals(map.get(empKeys))))
由於您的地圖是原始地圖,因此不是通用類型(它的值不是String)。 您已將此地圖定義為:
HashMap map2=new HashMap();
HashMap map3=new HashMap();
嘗試使其:
Map<Integer, String> map2 = new HashMap<Integer, String>();
Map<Integer, String> map3 = new HashMap<Integer, String>();
您需要使empDetails
也成為一個映射:
final Map<Integer, EmployeeVO> empDetails = new HashMap<Integer, EmployeeVO>();
並具有如下process
方法:
void process(final Map<Integer, Integer> map1,
final Map<Integer, String> map, final Map<Integer, EmployeeVO> empDetails) {
final Iterator<Integer> keys = map1.keySet().iterator();
while (keys.hasNext()) {
EmployeeVO empVO = new EmployeeVO();
Integer empId = keys.next();
empVOsetEmpId(empId);
empVO.setEmpAmount(map1.get(empId));
if (("Y".equals(map.get(empId))))
empVO setInd("Y");
else
empVO setInd("N");
empDetails.put(empId, empVO);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.