16

我有一个正在为我的 Java 类工作的项目(显然),我一定错过了关于如何与 TreeMaps 交互的讲座。我不知道我在用这部分做什么,也没有从谷歌那里得到很多帮助。

对于程序中的第一种情况,我必须打印 TreeMap 的所有值。以下是我提供的代码以及我使用它完成的工作。万一A是我的,但它不起作用。任何帮助,将不胜感激。

import java.util.Scanner;
import java.util.Set;
import java.util.Map;
import java.util.TreeMap;
import java.io.File;
import java.io.FileNotFoundException;

public class prog7 {
 public static void main(String args[])
 throws FileNotFoundException
 {
Scanner kb=new Scanner(System.in);

/*here, add code to declare and create a tree map*/
TreeMap treeMap = new TreeMap();

/*here, add code to declare a variable and
 let it be the key set of the map
 */
String key;

//temporary variables
String tempWord;
String tempDef;

//the following code reads data from the file glossary.txt
//and saves the data as entries in the map
Scanner infile=new Scanner(new File("glossary.txt"));

while(infile.hasNext())
{
  tempWord=infile.nextLine();
  tempDef=infile.nextLine();

  /*here, add code to add tempWord and tempDef
   as an entry in the map
   */
  treeMap.put(tempWord, tempDef);

}
infile.close();

while(true)
{
  System.out.println();
  System.out.println();

  //show menu and prompt message
  System.out.println("Please select one of the following actions:");
  System.out.println("q - Quit");
  System.out.println("a - List all words and their definitons");
  System.out.println("b - Enter a word to find its definition");
  System.out.println("c - Add a new entry");
  System.out.println("d - Delete an entry");
  System.out.println("Please enter q, a, b, c or d:");

  String selection=kb.nextLine();  //read user's selection
  if (selection.equals("")) continue; //if selection is "", show menu again

  switch (selection.charAt(0))
  { 
    case 'q':
      System.out.println("\nThank you.");
      return;

      /*write code for the cases 'a','b','c' and 'd'
       so that the program runs as in the sample run
       */

    case 'a':
       for (String treeKey : treeMap.keySet())
          System.out.println(treeKey);


    break;
4

7 回答 7

20

迭代 entrySet 而不是 keySet。你会得到一组Map.Entry<K, V>有方便getKey()getValue()方法。

也就是说,Java 的标准 Map 实现有一个 toString() 的实现,可以满足您的需求。当然,我认为你只会因为重新实现它而获得积分,而不是因为巧妙地避免它......

for (Map.Entry<K, V> entry : myMap.entrySet()) {
     System.out.println("Key: " + entry.getKey() + ". Value: " + entry.getValue());
}
于 2011-04-22T15:55:37.330 回答
9

您可以使用 entrySet()。java中的每个地图都有这个方法。

Map<String, String> tree = new TreeMap<String, String>();
tree.put("param1", "value1");
tree.put("param2", "value2");
for (Entry<String, String> entry : tree.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();

    System.out.printf("%s : %s\n", key, value);
}
于 2011-04-22T16:00:47.217 回答
2
for (String treeKey : treeMap.keySet())

这给了你钥匙。

treeMap现在在该循环中,使用键 ( )获取每个值treeKey,然后打印它。

于 2011-04-22T15:51:49.153 回答
1

You can use treeMap.get(treeKey) inside your loop to get the value for the key. Since this value is a string, you could just do something like:

System.out.println("The value for the current key is " + (String)treeMap.get(treeKey));
于 2011-04-22T15:53:20.777 回答
0

遍历键集然后检索每个值的效率低于遍历条目集( getEntries())。在前一种情况下,getValue()每次都必须执行新的查找,而getEntries()可以简单地返回地图的全部内容。

如果您尝试在映射键的迭代中检索值,静态分析器(例如 FindBugs)会给您一个警告。

于 2011-04-22T16:00:34.083 回答
0

not specifically about TreeMaps, but about Maps in general - I like this first answer, using Guava: Convert java Map to custom key=value string

于 2015-10-20T02:43:03.543 回答
0

使用 Java 8+,不需要循环:lambda 表达式使您能够以简洁的单行方式打印所有键和/或值:

map.forEach((key, value) -> System.out.println(key + " " + value));
于 2021-03-12T18:07:56.030 回答