简体   繁体   中英

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++)?

ps sorry for my English

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:

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:

You can have a look at the official documentation here

I think you can use an iterator to traverse on the map's keyset to achieve what you want. Sample code here:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Test {

public static void main(String[] args) {

    Map<Integer, String> map = new HashMap<Integer, String>() {
        {
            put(1, "One");
            put(2, "Two");
            put(3, "Three");
            put(4, "Four");
            put(5, "Five");
        }
    };


    Iterator<Integer> iter = map.keySet().iterator();

    while(iter.hasNext()){
        System.out.println(iter.next());
    }
}

LinkedList类有一个listIterator方法,可以帮助您在两个方向上遍历

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM