0

以下のコードでハッシュマップ リストを反復処理すると、キーと値が次のように取得されます。

    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

Use a LinkedHashMap and the order you put entries in the map will be the same order you iterate over them.

于 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 に答える