If .NET has a SortedDictionary object ... what is this in Java, please? I also need to be able to retrieve an Enumeration
(of elements), in the Java code .. so I can just iterate over all the keys.
I'm thinking it's a TreeMap ? But I don't think that has an Enumeration
that is exposed?
Any ideas?
SortedDictionary, SortedList, and SortedSet are collection classes that store key-value pairs and can be sorted based on the keys. A SortedSet is a collection that is maintained in sorted order. A SortedList is a collection that lets you retrieve the keys and/or values using indexes.
A SortedDictionary is implemented as a binary search tree. Therefore, accessing an element is O(lg(n)). A Dictionary is a hash table, and has a complexity of O(1) for access. A SortedDictionary is quite useful when you need the data to be sorted (a Dictionary has no defined order).
SortedDictionary is implemented with Binary Search Tree, while SortedList is implemented with two internal arrays for keys and values, respectively. SortedList is more memory-efficient than SortedDictionary, and SortedList is faster than SortedDictionary when it needs to go through all items at once.
What you need is entrySet() method of SortedMap (TreeMap).
TreeMap
would be the right choice. As for the Collection of all the keys (or values), any Map
exposes keySet()
and values()
.
EDIT (to answer your question with code tags). Assuming you have a Map<String, Object>
:
for (String key : map.keySet()) {
System.out.println(key); // prints the key
System.out.println( map.get(key) ); // prints the value
}
You can also use entrySet()
instead of keySet()
or values()
in order to iterate through the key->value pairs.
TreeMap
is probably the closest thing you're going to find.
You can iterate over the keys by calling TreeMap.keySet();
and iterating over the Set that is returned:
// assume a TreeMap<String, String> called treeMap
for(String key : treeMap.keySet())
{
string value = treeMap[key];
}
It would be the equivalent of:
// assume a SortedDictionary called sortedDictionary
foreach(var key in sortedDictionary.Keys)
{
var value = sortedDictionary[key];
}
// assume TreeMap<String, String> called treeMap
for (Map.Entry<String, String> entry : treeMap.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
}
Which is the equivalent to the following .NET code:
// assume SortedDictionary<string, string> called sortedDictionary
foreach(KeyValuePair<string, string> kvp in sortedDictionary)
{
var key = kvp.Key;
var value = kvp.Value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With