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!
Split the map viewOn the View tab, in the Window group, click Split, and then click Horizontal or Vertical. Right-click the map's workbook tab and click Split Map Horizontally or Split Map Vertically. You can drag the splitter bar between the windows to change their size.
First you split the String on basis of - , then you map like map(s -> s. split("~", 2)) it to create Stream<String[]> like [name, peter][add, mumbai][md, v][refNo, ] and at last you collect it to toMap as a[0] goes to key and a[1] goes to value.
HashMap. clone() method is present inside java. util package which typically is used to return a shallow copy of the mentioned hash map. It just creates a copy of the map.
Do you have to use HashMap
?
TreeMap
is really good for this kind of things. Here's an example (note that 0, 50, and 99 are map keys, not indices):
TreeMap<Integer, Integer> sorted = new TreeMap<Integer, Integer>(bigMap);
SortedMap<Integer, Integer> zeroToFortyNine = sorted.subMap(0, 50); // toKey inclusive, fromKey exclusive
SortedMap<Integer, Integer> fiftyToNinetyNine = sorted.subMap(50, true, 99, true);
You can use Guava Iterables partition method and Java stream interface to solve it.
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public static <K, V> List<Map<K, V>> split(Map<K, V> map, int size) {
List<List<Map.Entry<K, V>>> list = Lists.newArrayList(Iterables.partition(map.entrySet(), size));
return list.stream()
.map(entries ->
entries.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
)
.collect(Collectors.toList());
}
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