【问题标题】:Get specific Data from inside a HashMap从 HashMap 中获取特定数据
【发布时间】:2015-09-26 23:38:02
【问题描述】:

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

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

这是我当前的输出:

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

}

【问题讨论】:

  • 您是否要打印所有按值排序的地图条目?

标签: java dictionary hash hashmap output


【解决方案1】:

与其依赖HashMap 的默认toString() 实现,不如直接遍历条目:

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

【讨论】:

  • 你必须原谅我,因为我的理解还很薄弱。我一直在尝试实现这一点,但是我要么得到从我正在阅读的文本文件中打印的每一行的列表,要么什么都没有?我尝试将“For”放在“While”上方,然后将另一半放在周围以使其正常工作?
  • @Masch:该代码将打印地图中的每个条目,格式为{key}: ${value}。现在,如果您的地图内容不是您想要的,那就另当别论了。
  • 我想我开始看到了。虽然我对这个地图的东西很薄弱,但我猜地图已经从文本文件中获取了所有内容,在这里它打印出了每一行的名称,然后是 $number。我不知道我之前的问题 [link]stackoverflow.com/questions/30804965/… [/link] 是否导致我对这个问题的措辞有误?顺便说一句,我在这里造成的麻烦表示歉意。
  • 使用您发布的代码,您不应该有很多行。你确定你没有在你的while循环中留下一个System.out.println电话吗?
  • 如果将 for 循环放在 while 循环中,我只会打印出从文本文件中读取的所有行。如果我取出 'System.out.println' 行,我不会显示任何输出。我试图不将“for”循环放在“while”中,但我似乎无法在其他地方使用它来获得任何输出?
【解决方案2】:

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

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

【讨论】:

  • 如果您没有任何理由(例如删除某些元素),请不要显式使用迭代器。而是使用增强的循环,它可以很好地包装你的 while 循环(看看乔恩的答案)。也不要使用原始类型。
猜你喜欢
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
  • 2016-03-10
  • 2017-07-19
  • 1970-01-01
  • 2019-12-07
  • 2011-07-22
相关资源
最近更新 更多