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).
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.
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