Java 如何将元素添加到对象的hashmap,List<;对象>;

Java 如何将元素添加到对象的hashmap,List<;对象>;,java,hashmap,Java,Hashmap,我有一个来自dao的列表,我想把这个列表放在HashMap>中,我的列表可以包含一个具有多个参数的服务,比如serviceId=3。在我最后的HashMap中,结果如下:{service1=[100,A],service2=[101,A],service3=[Parameter[102,B],Parameter[103,B],Parameter[104,C]} serviceId paramId type 1 100 A 2 10

我有一个来自dao的列表,我想把这个列表放在HashMap>中,我的列表可以包含一个具有多个参数的服务,比如serviceId=3。在我最后的HashMap中,结果如下:
{service1=[100,A],service2=[101,A],service3=[Parameter[102,B],Parameter[103,B],Parameter[104,C]}

serviceId   paramId   type
 1            100      A
 2            101      A
 3            102      B
 3            103      B
 3            104      C
Service.java

private int id;
//Getters+Setters
Parameter.java

private int id;
private String type;
//Getters+Setters
Test.java

 List result = dao.getServiceParam();
HashMap<Service,List<Parameter>> mapList = new HashMap<Service, List<Parameter>>();   
if(!result.isEmpty()) {             
for (int i=0; i< result.size(); i++) {
    Object[] line = (Object[])result.get(i);        
    if ((BigDecimal) line[0]!=null) {

    }
    }
    }      
List result=dao.getServiceParam();
HashMap mapList=新建HashMap();
如果(!result.isEmpty()){
对于(int i=0;i
如果((BigDecimal)行[0]!=null&&line.length>2){
服务服务=新服务((整数)行[0]);
参数param=新参数((整数)行[1],(字符串)行[2]);
List paramList=mapList.get(serv);
if(paramList==null){
paramList=新的LinkedList();
}
paramList.add(param);
put(serv,paramList);
}
您可以用上面的代码替换空if。 我相信这应该符合你的目的。但要运行上述代码,您应该满足以下条件

  • 您的参数和服务类应该有一个构造函数
  • 您应该已经基于服务类的id属性重写了hashcode和equals方法
  • 如果您希望在任何字段处为null。请处理这个问题
  • if ((BigDecimal) line[0]!=null && line.length>2) {
    
        Service serv = new Service((Integer) line[0]);
        Parameter param = new Parameter((Integer)line[1],(String) line[2]);
        List<Parameter> paramList=mapList.get(serv);
        if (paramList==null){
            paramList = new LinkedList<Parameter>();
        }
    
        paramList.add(param);
    
        mapList.put(serv, paramList);
    }