2012-08-02 103 views
0

當我遍歷我用下面的代碼HashMap的名單,我拿到鑰匙和值返回列表迭代

System.out.println(" (" + key + "," + value + ")") 

但我想我的價值觀被返回

重點1 :值1

密鑰1:值2

鍵2:值1

鍵2:VA魯2 ...等等。有人可以幫我嗎。

public static void main(String[] args) { 
    Map<String, List<String>> conceptMap = new HashMap<String, List<String>>(); 
    Map<String, List<String>> PropertyMap = new HashMap<String, List<String>>(); 
    try{ 
    Scanner scanner = new Scanner(new FileReader("C:/")); 

     while (scanner.hasNextLine()){ 
     String nextLine = scanner.nextLine(); 
     String [] column = nextLine.split(":"); 
     if (column[0].equals ("Property")){ 
     if (column.length == 4) { 
     PropertyMap.put(column [1], Arrays.asList(column[2], column[3])); 
      } 
     else { 
     conceptMap.put (column [1], Arrays.asList (column[2], column[3])); 
      } 
     } 
     } 
     Set<Entry<String, List<String>>> entries =PropertyMap.entrySet(); 
      Iterator<Entry<String, List<String>>> entryIter = entries.iterator(); 
      System.out.println("The map contains the following associations:"); 
      while (entryIter.hasNext()) { 
      Map.Entry entry = (Map.Entry)entryIter.next(); 
      Object key = entry.getKey(); // Get the key from the entry. 
      Object value = entry.getValue(); // Get the value. 
      System.out.println(" (" + key + "," + value + ")"); 
      } 
     scanner.close(); 

     } 

     catch (Exception e) { 
     e.printStackTrace(); 
     } 

回答

0

使用地圖一LinkedHashMap和命令你put作品將您遍歷它們的順序相同。

2

替換此:

System.out.println(" (" + key + "," + value + ")"); 

for (Object listItem : (List)value) { 
    System.out.println(key + ":" + listItem); 
} 
0
while (entryIter.hasNext()) { 

     //... 
     String key = entry.getKey(); // Get the key from the entry. 
     List<String> value = entry.getValue(); // Get the value. 

     for(int i = 0; i < value.size(); i++) { 
      System.out.println(" (" + key + "," + value.get(i) + ")"); 
     } 
} 
0

所以,你想在你的清單打印出來的價值觀?替換:

Object value = entry.getValue(); // Get the value. 
System.out.println(" (" + key + "," + value + ")"); 

有了這個:

List<String> value = entry.getValue(); 
for(String s : value) { 
    System.out.println(key + ": " + s); 
} 
+0

Thnak你這麼多。有用:) – user1549861 2012-08-02 19:46:53