Home > Software design >  How to get the next element to the current in a LinkedHashMap?
How to get the next element to the current in a LinkedHashMap?

Time:10-31

Let's say I have the LinkedHashMap with some unknown data inside.

//==================
Map< Integer, String > map = new LinkedHashMap<>();
map.put(10, "C");
map.put(20, "C  ");
map.put(50, "JAVA");
map.put(40, "PHP");
map.put(30, "Kotlin");
//=============

And I know just the key = 50;

I am wondering what is the best way to get the next element to the element that I have by this key (50)? This is not a multi-threaded application. I don't worry about thread-safety.

I don't like the way to iterate all keys through entrySet from the beginning.

It would be great to somehow get access to the next() of LinkedHashMaps Entry.

CodePudding user response:

This is LinkedHashMap so it remembers the order of elements insertion.

public static Map.Entry<Integer, String> getNextEntry(LinkedHashMap<Integer, String> map, Integer key) {
    List<Integer> keys = new ArrayList<>(map.keySet());
    int index = keys.indexOf(key);

    if (index < 0 || index >= keys.size() - 1)
        return null;

    int k = keys.get(index   1);
    return Map.entry(k, map.get(k));
}

Or you can use Iterator:

public static Map.Entry<Integer, String> getNextEntry(LinkedHashMap<Integer, String> map, Integer key) {
    boolean found = false;

    for (Map.Entry<Integer, String> entry : map.entrySet()) {
        if (found)
            return Map.entry(entry.getKey(), entry.getValue());
        if (entry.getKey().intValue() == key)
            found = true;
    }

    return null;
}

CodePudding user response:

LinkedHashMap doesn't offer a functionality which would allow finding the next key or entry.

In case if you simply don't want to bother with managing iteration yourself manually, then sure you can alternate this process, but keep in mind that the iteration should happen somewhere anyway.

Stream API

Alternatively you can make use of the Stream API if you don't want to bother with loops.

public static Optional<Map.Entry<Integer, String>> getNextEntry(Map<Integer, String> map,
                                                                int previous) {
    return map.entrySet().stream()
        .dropWhile(entry -> entry.getKey() != previous) // discard the entries, until the target key has been encountered
        .skip(1)      // skip the entry with the target key
        .findFirst(); // grab the next entry and return it as an Optional (because the next entry might not exist)
}

TreeMap

However, you would be able to navigate through the keys of the map if you were using a TreeMap.

TreeMap maintains a red-black tree under the hood, and it keep the entries in sorted order based on keys. And it offers various method like higherEntry(), higherKey().

NavigableMap<Integer, String> map = new TreeMap<>();

// populating the map
    
int key = 50;
    
Map.Entry<Integer, String> next = map.higherEntry(key);
  • Related