繁体   English   中英

从HashMap内部获取特定数据

[英]Get specific Data from inside a HashMap

首先,我必须道歉,因为我不确定如何恰当地称呼我的头衔。

但是,我面临的问题是另一个问题的延续,使我离完成此特定程序仅一步之遥。 问题到了。

这是我当前的输出:

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());
}

使用Iterator遍历Map并打印其所有内容,以下示例将为您工作。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM