求助List<Map> 合并同一num的所有name值
List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
Map<String, Object> map1=new HashMap<String, Object>();
map1.put("name", "jack");
map1.put("num", "篮球队");
Map<String, Object> map2=new HashMap<String, Object>();
map2.put("name", "tom");
map2.put("num", "篮球队");
Map<String, Object> map3=new HashMap<String, Object>();
map3.put("name", "tim");
map3.put("num", "篮球队");
Map<String, Object> map4=new HashMap<String, Object>();
map4.put("name", "hhs");
map4.put("num", "足球队");
Map<String, Object> map5=new HashMap<String, Object>();
map5.put("name", "www");
map5.put("num", "足球队");
list.add(map1);
list.add(map2);
list.add(map3);
list.add(map4);
list.add(map5);
System.out.println(list.size());
for (int i = 0; i < list.size(); i++) {
//System.out.println(list.get(i).get("name"));
//应该咋写啊。。。
}
效果:
jack,tom,tim是篮球队的
hhs,www是足球队的 list?map
[解决办法]
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
public class Teams{
public static void main(String args[]){
List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
Map<String, Object> map1=new HashMap<String, Object>();
map1.put("name", "jack");
map1.put("num", "basketball");
Map<String, Object> map2=new HashMap<String, Object>();
map2.put("name", "tom");
map2.put("num", "basketball");
Map<String, Object> map3=new HashMap<String, Object>();
map3.put("name", "tim");
map3.put("num", "basketball");
Map<String, Object> map4=new HashMap<String, Object>();
map4.put("name", "hhs");
map4.put("num", "football");
Map<String, Object> map5=new HashMap<String, Object>();
map5.put("name", "www");
map5.put("num", "football");
list.add(map1);
list.add(map2);
list.add(map3);
list.add(map4);
list.add(map5);
System.out.println(list.size());
List<String> basketball = new ArrayList<String>();
List<String> football = new ArrayList<String>();
for(Map<String, Object> theMap : list){
if (theMap.get("num").equals("basketball")){
basketball.add((String)theMap.get("name"));
}else{
football.add((String)theMap.get("name"));
}
}
for(String name : basketball){
System.out.print(name + ", ");
}
System.out.println("belong to basketball team");
for(String name : football){
System.out.print(name + ", ");
}
System.out.println("belong to football team");
}
}