Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get submap of LinkedHashMap by element index?

Tags:

java

I am trying to get a submap of LinkedHashMap based on element index. Am I reinventing the wheel here? Sounds like this should be somewhere in API already:

public <K,V> LinkedHashMap<K,V> subMap(LinkedHashMap<K,V> map, int fromIndex, int toIndex) {
    LinkedHashMap<K,V> result = new LinkedHashMap<K,V>();

    int i=0;
    for(Map.Entry<K,V> entry : map.entrySet()) {
        if(i >= fromIndex && i < toIndex) {
            result.put(entry.getKey(), entry.getValue());
        }
        i++;
    }

    return result;
}

Is this the way to go or there are some other better/existing solutions (within Java 6 API).

like image 424
serg Avatar asked May 14 '12 18:05

serg


1 Answers

NavigableMap allows you to get a sub-map back, but it requires that you specify a 'from key' and a 'to key', so you can't do it purely on index.

I'm not aware of any other way of doing this via the standard API.

like image 129
gus Avatar answered Oct 18 '22 18:10

gus