user2803053
user2803053

Reputation: 59

Iterate through a binary search tree

I want to go through every item in a dictionary in Java. To clarify what I want to do, this is the C# code:

Dictionary<string, Label> LableList = new Dictionary<string, Label>();
foreach (KeyValuePair<string, Label> z in LabelList) { … }

Upvotes: 0

Views: 438

Answers (3)

Nikunj Banka
Nikunj Banka

Reputation: 11395

What you want to use is the HashMap or the TreeMap to implement a dictionary in Java. The HashMap class uses hashing to maintain the dictionary while TreeMap uses a Red Black Tree(a variant of the BST) to maintain the dictionary.

Moreover, if the mapping is from a String to a class Label, then can use the following code. You will also have to import java.util.* and declare the Label class separately for the code to run successfully.

    TreeMap<String, Label> map = new TreeMap<String, Label>();
    for (Map.Entry<String, Label> entry : map.entrySet()){
         System.out.println(entry.getKey() + "/" + entry.getValue());
    }

Upvotes: 0

Mike Samuel
Mike Samuel

Reputation: 120586

temp += ("<" + it.next() + ", " + bstd.getValue(it.next()) + ">");

is calling next twice per hasNext(). Store the next value in a local variable.

Object current = it.next();
temp += ("<" + current + ", " + bstd.getValue(current) + ">");

Upvotes: 1

Vince
Vince

Reputation: 15128

To iterate without map iterator:

 for(Type t : map.values().toArray(new Type[map.size()])) {
      //values
 }

Although I haven't used this in a while, there's probably a cleaner way of doing this

Upvotes: 0

Related Questions