从HashMap中获取特定数据

时间:2015-07-08 20:35:45

标签: java dictionary hash hashmap output

首先,我必须道歉,因为我不确定如何很好地说出我的头衔。

然而,我面临的问题是继续提出另一个问题,这使我更接近完成这个特定的计划。尽管如此。

这是我目前的输出:

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

这些都在HashMap中,我打印出来,虽然我需要做的是使这个输出更具可见性,我想这导致需要从Map内部操作/获取某些数据,然后使其呈现。< / p>

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

Jack: $191
Mike: $52
Joe: $46

我对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: $191
      Mike: $52
      Joe: $46
  */
}

}

2 个答案:

答案 0 :(得分:2)

好而不是依赖于toString()的默认HashMap实现,只需循环条目:

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

答案 1 :(得分:0)

使用Iterator遍历Map并打印其所有内容,以下示例应该适合您。

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