我现在有不确定数量的数据,我想把这些数据都放进map中去。
例如:
数据:英文成绩:123,100,99
数学成绩:100,90,89
语文成绩:90,78,97
政治成绩:100,29,20
我想把这些数据放进map中。尽量写的详细点。谢谢
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.Collection.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Map map = new HashMap();
map.put("英文", new int[] { 123, 100, 99 });
map.put("数学", new int[] { 100, 90, 89 });
map.put("语文", new int[] { 90, 78, 97 });
map.put("政治", new int[] { 100, 29, 20 });
for (Object obj : map.keySet())
{
System.out.println("--------------");
System.out.println(obj);
for (Object x : (int[])map.get(obj))
System.out.println(x);
}
}
}
--------------
政治
100
29
20
--------------
英文
123
100
99
--------------
数学
100
90
89
--------------
语文
90
78
97
一、需求分析
1、从需求来看,基本数据结构是确定了:科目和科目中多个具体的数据。
2、要求数据结构下的科目和科目中的具体数量是不确定的,也就是可以延伸的。
3、在构造方法时可扩展性是首要考虑因素,因此科目和分数都需要利用集合对象。
二、具体实现
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Test {
private static Map<String,List<String>> map = new HashMap<>();
/**
* 添加一组对应关系
* @param subject
* @param scores
* @return
*/
public static Map<String,List<String>> organizeMap(String subject,Object scoreObj){
if(subject==null||scoreObj==null)
throw new IllegalStateException("The paramater map must be specified!");
if(scoreObj instanceof List){
if(map.containsKey(subject)){
map.get(subject).addAll((List)scoreObj);
}else{
map.put(subject, (List)scoreObj);
}
}else if(scoreObj instanceof String){
if(map.containsKey(subject)){
map.get(subject).add((String)scoreObj);
}else{
List<String> _list = new ArrayList();
_list.add((String)scoreObj);
map.put(subject,_list);
}
}else{
throw new IllegalArgumentException("The second argument is illegal!");
}
return map;
}
public static void main(String[] args){
List<String> list = new ArrayList<>();
list.add("ZhuChengfeng");
list.add("LiGaoqing");
list.add("Wangjie");
String param = "BObo";
organizeMap("ESB",list);
organizeMap("ESB",param);
organizeMap("Zhicall","bobo");
for(Entry<String,List<String>> entry:map.entrySet()){
System.out.println(entry.getKey()+"==="+entry.getValue());
}
}
}
三、输出结果
Zhicall===[bobo]
ESB===[ZhuChengfeng, LiGaoqing, Wangjie, BObo]
搞这么复杂,,其实没必要用map,pojo,普通java对象就行了
Map String,List grade=new HashMap String,List();
List Integer englishList=new ArrayList Integer();
englishList.add(123);
englishList.add(99);
englishList.add(100);
grade.put("英文成绩",englishList);
依此类推