开发者

How would I print all values in a TreeMap?

I have a project that I'm working on for my Java class (obviously) and I must have missed the lecture on how to interact with TreeMaps. I have no idea what I'm doing with this part and I'm not finding a lot of help from Google.

For the first case in the program, I have to print all开发者_JAVA百科 values of a TreeMap. The following is the code I was provided and the work I have done with it. Everything in case A is mine, but it isn't working. Any help would be appreciated.

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;


Iterate over the entrySet rather than the keySet. You get a set of Map.Entry<K, V> which have convenient getKey() and getValue() methods.

That said, Java's standard Map implementations have an implementation of toString() that does what you want. Of course, I reckon you'll only get points for reimplementing it, not for cleverly avoiding it...

for (Map.Entry<K, V> entry : myMap.entrySet()) {
     System.out.println("Key: " + entry.getKey() + ". Value: " + entry.getValue());
}


You can use entrySet(). Every Map in java have this method.

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


for (String treeKey : treeMap.keySet())

That gives you the keys.

Now in that loop, get each value from the treeMap using the key (treeKey), and print it.


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


With Java 8+ there is no need for a loop: lambda expressions enable you to print all keys and/or values in a neat one-liner:

map.forEach((key, value) -> System.out.println(key + " " + value));


Iterating over the set of keys and then retrieving each value is less efficient than iterating over the set of entries (getEntries()). In the former case, getValue() will have to perform a new lookup each time, while getEntries() can simply return the entire contents of the map.

Static analysers such as FindBugs will give you a warning if you try to retrieve a value inside a iteration over the map's keys.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜