java - 从 HashMap 中获取特定数据

标签 java dictionary hash hashmap output

首先,我必须道歉,因为我不确定如何正确表达我的标题。

然而,我面临的问题是另一个问题的延续,它使我离完成这个特定的程序又近了一步。但还是要解决这个问题。

这是我当前的输出:

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

这些位于 HashMap 内部,我将其打印出来,但我需要做的是使此输出更美观,我猜这会导致需要从 Map 内部操作/获取某些数据,然后使其易于呈现。

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

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
  */
}

}

最佳答案

好吧,不要依赖 HashMap 的默认 toString() 实现,只需循环遍历条目即可:

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

关于java - 从 HashMap 中获取特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31303191/

相关文章:

ruby - 从散列中移除 nil 值

java - 膨胀类 android.fragment.app.FragmentContainerView 时出错,有人可以告诉我我缺少什么吗

java - 如何解析没有对象名称的 JSON 数组

python - 获取Python中字典字典中所有键的数量

网址上的 AngularJS "#!"

c++ - 需要将字符串存储为某些快速数据结构中的对象的 id

java - 从 ParameterMap 对象创建哈希

java - 如何克服 Java 静态 Main() 方法的限制

python - 制作一个新字典,删除一些键并且不更改原始字典

dictionary - 我可以有检查键是否在 map 中的功能吗?