RNO - 1 year ago 757

Java Question

I was wondering if it is possible to split a HashMap into smaller sub-maps.

In my case I have a HashMap of 100 elements and I would like to create 2 (or more) smaller HashMaps from the original one, the first containing the Entries from 0 to 49, the second containing the Entries from 50 to 99.

`Map <Integer, Integer> bigMap = new HashMap <Integer, Integer>();`

//should contains entries from 0 to 49 of 'bigMap'

Map <Integer, Integer> smallMap1 = new HashMap <Integer, Integer>();

//should contains entries from 50 to 99 of 'bigMap'

Map <Integer, Integer> smallMap2 = new HashMap <Integer, Integer>();

Any suggestions? Many thanks!

Answer Source

Do you have to use `HashMap`

?

`TreeMap`

is really good for this kind of things. Here's an example.

```
TreeMap<Integer, Integer> sorted = new TreeMap<Integer, Integer>(bigMap);
SortedMap<Integer, Integer> zeroToFortyNine = sorted.subMap(0, 50);
SortedMap<Integer, Integer> fiftyToNinetyNine = sorted.subMap(50, 100);
```