7

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

1
  • How will the returned Map be used? Can you use an iterator instead? If so, you could return a custom iterator that returns values (or Map.Entries) between the specified index range. Keep in mind concurrency issues when dealing with index ranges of a collection. Commented May 14, 2012 at 18:59

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually any SortedMap will provide submap(...)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.