2012-10-19 30 views
2

怎麼做的Hashmap我有一個像如何使用散列表存儲值的列表?使用以下格式

{"tname":"Learning Ratio and Proportion Concepts and practice assessment","gname":"Sixth grade"}, 
{"tname":"Number System","gname":"Sixth grade"}, 
{"tname":"quations and expression","gname":"Seventh grade"},{"tname":"Geometry","gname":"Seventh grade"} 

我希望保存爲

list<String>={"Sixth grade","Seventh grade"} 

list(list<String>)={{"Learning Ratio and Proportion Concepts and practice assessment","Number System"},{"quations and expression","Geometry"}} 

任何一個可以幫助我感謝的價值列表...

+0

鍵值只能在地圖中出現*一次*。你不止一次使用過tname和gname。你想要3張地圖還是1張地圖? –

+0

只有一張地圖... – sureshkumar

+0

然後tname和gname只能在地圖中出現一次。 –

回答

0

我猜你想存儲書籍每檔次需要。

enum Grades 
    { 
    SIXTH_GRADE, SEVENTH_GRADE; 
    } 

    public static void main(String[] args) throws IOException 
    { 
    Map<Grades, List<String>> literature = new HashMap<Grades, List<String>>(); 
    literature.put(Grades.SIXTH_GRADE, new ArrayList<String>(Arrays.asList("Learning Ratio and Proportion Concepts and practice assessment","Number System"))); 
    literature.put(Grades.SEVENTH_GRADE, new ArrayList<String>(Arrays.asList("Equations and expression","Geometry"))); 

    // get books for 6th grade 
    List<String> books6th = literature.get(Grades.SIXTH_GRADE); 

    for (String book : books6th) 
     System.out.println(book); 

    // get books for 7th grade 
    List<String> books7th = literature.get(Grades.SEVENTH_GRADE); 

    Collection<List<String>> allBooks = literature.values(); // tname data 
    Set<Grades> allGrades = literature.keySet(); // data associated with gname 
    } 

我甚至會考慮創建像ISBN號,價格等成員class Book但是,這取決於你的使用情況。

我在這裏使用了枚舉,而不是字符串,所以地圖不太容易出錯。例如,如果有人偶爾寫"6th grade"而不是"sixth grade",當然你也可以使用字符串常量。

隨着枚舉你可以使用一個EnumMap,而不是像HashMap

Map<Grades, List<String>> literature = new EnumMap<Grades, List<String>>(Grades.class);

0

使用ArrayList與哈希地圖

HashMap<String,ArrayList<String[]>> map = new HashMap<String,ArrayList<String[]>>(); 

    ArrayList<String[]> theList1 = new ArrayList()<String[]>(); 

    theList1.add(new String[] {"Learning Ratio and Proportion Concepts and practice assessment","Sixth grade"}); 

    map.put("tname", theList1); 
+0

我得到類似HashMap的參數的錯誤數量錯誤;它不能用參數參數化> – sureshkumar

+2

HashMap需要2個參數,你只能放一個。例如:HashMap > –

+0

是正確更新的答案 –

相關問題