从 HashMap 中获取特定数据

Get specific Data from inside a HashMap

首先,我必须道歉,因为我不确定如何用好我的标题。

然而,我面临的问题是另一个问题的延续,这个问题使我离完成这个特定程序又近了一步。不过问题来了。

这是我当前的输出:

Income
{Jack=46, Mike=52, Joe=191}

这些在 HashMap 里面,我打印出来了,我需要做的是让这个输出更像样,我想这导致需要 manipulate/get 来自地图内部的某些数据,然后制作它像样的。

我的目标是让我的输出看起来像这样:

Jack: 1
Mike: 
Joe: 

我对 Java 和一般编程还是很陌生,所以我只是想知道这是否可能,或者我是否一开始就以错误的方式解决了这一切?

下面是我的代码:

public static void main(String[] args) {

  String name;
  int leftNum, rightNum;

  //Scan the text file
  Scanner scan = new Scanner(Test3.class.getResourceAsStream("pay.txt"));

  Map < String, Long > nameSumMap = new HashMap < > (3);
  while (scan.hasNext()) { //finds next line
    name = scan.next(); //find the name on the line
    leftNum = scan.nextInt(); //get price
    rightNum = scan.nextInt(); //get quantity

    Long sum = nameSumMap.get(name);
    if (sum == null) { // first time we see "name"
      nameSumMap.put(name, Long.valueOf(leftNum + rightNum));
    } else {
      nameSumMap.put(name, sum + leftNum + rightNum);
    }
  }
  System.out.println("Income");
  System.out.println(nameSumMap); //print out names and total next to them

  //output looks like this ---> {Jack=46, Mike=52, Joe=191}

  //the next problem is how do I get those names on seperate lines
  //and the total next to those names have the symbol $ next to them.
  //Also is it possible to change = into :
  //I need my output to look like below
  /*
      Jack: 1
      Mike: 
      Joe: 
  */
}

}

嗯,不要依赖 HashMap 的默认 toString() 实现,只需循环条目:

for (Map.Entry<String, Long> entry : nameSumMap.entrySet()) {
    System.out.println(entry.getKey() + ": $" + entry.getValue());
}

使用迭代器遍历 Map 并打印其所有内容,下面的示例应该适合您。

Iterator iterator = nameSumMap.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry mapEntry = (Map.Entry) iterator.next();
    System.out.println(mapEntry.getKey()
        + ": $" + mapEntry.getValue());
}