0

当我用下面的代码遍历我的 hashmap 列表时,我得到的键和值是

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

但我希望我的值返回为

键 1:值 1

键 1:值 2

键 2:值 1

键 2:值 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();
        } 
4

4 回答 4

2

替换这个:

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

for (Object listItem : (List)value) {
    System.out.println(key + ":" + listItem);
}
于 2012-08-02T19:20:57.757 回答
0

使用 aLinkedHashMap并且您put在地图中输入的顺序将与您遍历它们的顺序相同。

于 2012-08-02T19:18:42.237 回答
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) + ")" );
      }
}
于 2012-08-02T19:23:19.573 回答
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);
}
于 2012-08-02T19:23:55.390 回答