英文:
How to add element to hashmap of Object,List<Object>
问题
import java.util.List;
import java.util.Map;
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
List<Object[]> result = dao.getServiceParam();
Map<Service, List<Parameter>> mapList = new HashMap<Service, List<Parameter>>();
if (!result.isEmpty()) {
for (int i = 0; i < result.size(); i++) {
Object[] line = result.get(i);
if (line[0] != null) {
int serviceId = ((BigDecimal) line[0]).intValue();
int paramId = ((BigDecimal) line[1]).intValue();
String type = (String) line[2];
Service service = new Service(serviceId);
Parameter parameter = new Parameter(paramId, type);
if (!mapList.containsKey(service)) {
mapList.put(service, new ArrayList<Parameter>());
}
mapList.get(service).add(parameter);
}
}
}
}
}
class Service {
private int id;
public Service(int id) {
this.id = id;
}
// Getters + Setters
}
class Parameter {
private int id;
private String type;
public Parameter(int id, String type) {
this.id = id;
this.type = type;
}
// Getters + Setters
}
英文:
I have a list from dao, I want to put this list in a HashMap<Service,List<Paramter>>, my list can contain a service which have multiple parameters like the serviceId=3. In my final HashMap, the result looks like : {Service 1=[100,A],Service 2=[101,A],Service 3=[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) {
}
}
}
答案1
得分: 0
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);
}
英文:
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);
}
You can replace your empty if with the code above.
This should serve your purpose I believe. but to run the above code you should meet below conditions.
- your Parameter and Service class should have a constructor.
- you should have overridden the hashcode and equals methods based on id attribute of Service class
- If you expect null at any of the field. Please handle that.
专注分享java语言的经验与见解,让所有开发者获益!
评论