Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java container like c++ map

Are there any containers in Java which allows us to use iterator by key and which can go both to the next element and to the previous one (like maps in c++)?

p.s. sorry for my English

like image 634
AlexMalinin Avatar asked Dec 19 '22 17:12

AlexMalinin


1 Answers

A NavigableMap comes closest to std::map. The most commonly used implementation is TreeMap.

The NavigableMap contains a lot of methods to iterate in sorted order over the entries. The first loop iterates over all elements, whereas the second loop is restricted to a sub-range.

NavigableMap<String, Integer> map = ...;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    // ...
}
for (Map.Entry<String, Integer> entry
   : map.subMap("bar", "foo").entrySet()) {
    // ...
}

It is also possible to iterate from the beginning to a certain entry, or from a certain entry to the end. Take a look at the following methods:

  • subMap
  • headMap
  • tailMap

In C++, iterators are also used for a lot of other use cases. The Java iterators are very different, and can not be used in combination with mutating operations. In many cases, you have to use lookups by instead of iterations. For example, the following methods return the previous and next entry (in sorted order), if the key of the current entry is used:

  • lowerEntry
  • higherEntry
like image 147
nosid Avatar answered Dec 22 '22 08:12

nosid