15

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 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;
Lish
  • 197
  • 2
  • 2
  • 10

7 Answers7

19

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());
}
Xr.
  • 1,392
  • 12
  • 22
  • Is the entrySet a part of the Set class? I can't add any additional classes to the program. – Lish Apr 22 '11 at 15:58
  • No, it's part of the map: http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html#entrySet%28%29 – Xr. Apr 22 '11 at 15:59
  • ahh. Interesting. I might have to try that if I can't get something else working. I want to try and stick to what the professor is expecting as much as I can. Thanks for the heads up, though. I'll definitely look into it further if I don't use it now. – Lish Apr 22 '11 at 16:01
  • Unless you have more constraints than those you described, the entrySet should be fine: you still do most of the work and it's more efficient than a call to `get(key)` for each key. I edited my post to add an example. – Xr. Apr 22 '11 at 16:06
8

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);
}
Lynch
  • 8,224
  • 2
  • 21
  • 33
1
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.

Brian Roach
  • 72,790
  • 10
  • 128
  • 154
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));
dcp
  • 51,027
  • 19
  • 136
  • 157
  • Ahhh. So I would print all of them in the same way that I would print just one after a search. I see. It's so obvious. Sometimes I wonder why I'm a computer science major when I have moments like this. – Lish Apr 22 '11 at 15:55
  • @Lish - Yes, I provide an example println in my latest edit so you could see how to do it. Hope it's helpful. – dcp Apr 22 '11 at 15:56
  • ah, yes. that would make sense. – Lish Apr 22 '11 at 16:03
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

Community
  • 1
  • 1
ycomp
  • 6,614
  • 15
  • 50
  • 82
0

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.

JesperE
  • 59,843
  • 19
  • 133
  • 192
  • Do I need to make the treeMap object of another type in that case? I'm getting the following error if I try and use that command: `File: Z:\CS121\Project 7\prog7.java [line: 79] Error: Z:\CS121\Project 7\prog7.java:79: cannot find symbol symbol : method getEntries() location: class java.util.TreeMap` – Lish Apr 22 '11 at 16:09
  • 1
    Sorry. The method is called `entrySet`. But honestly, you should have been able to find that yourself. The API docs for the Map class are not difficult to find. – JesperE Apr 22 '11 at 19:14
0

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));
Philzen
  • 2,653
  • 23
  • 34