Map subsetting by keySet().toArray()

I recently faced a non-standard request, for which I implemented a solution that doesn't make me completely happy. But I have not much time to ponder of it, and it works. I write it down here, so that maybe someone (or myself in the future) could show me a better alternative.

Developing for Java 6, using just the core functionality. It is given a map of Strings and whatever, and an index of one of its elements, we want to reduce the original map to a subset such as: (1) the resulting map would contain 10 elements maximum, (2) the element given by index would be the first, (3) the traversing map order is preserved.

We don't know the actual type of the map object in input, we know only that it implements the Map interface, meaning that we can't use the handy SortedMap.subMap() method.

My first idea was iterating on the map associated entry set, removing all the items before the index, then executing a dummy loop for ten times, before removing the tail elements (if any). It works, but the central dummy loop is quite boring.

So I opted for going through the keySet map, converting it to an array, so that I could randomly access any element in it:
String[] keys = (String[])myMap.keySet().toArray(new String[myMap.size()]); // 1
for(int i = 0; i < first; ++i) // 2
    myMap.remove(keys[i]);

for(int i = first + max; i < keys.length; ++i) // 3
    myMap.remove(keys[i]);
1. This line is painful. Given a myMap object (it instantiates a class that implements the Map interface, as described above), we call on it keySet(), that returns a set, on it we call the toArray() method, that converts it to an array. I have already written something on the toArray() involuted syntax, using this overload we can specify the actual type of the returned array. 2. Assuming first is an int variable, representing the index of the elements we are interesting it, defined before this code snippet. Here we are removing the leading elements. 3. The max variable stores the maximum number of elements we want to have in the resized map. The effect is removing all the trailing elements.

Go to the full post