Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an HashMap in Java

Tags:

java

hashmap

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!

like image 255
RNO Avatar asked Jan 31 '13 15:01

RNO


People also ask

How do you split a map?

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.

How do I split a string and a store in maps?

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.

Can HashMap be cloned?

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.


2 Answers

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);
like image 94
sharakan Avatar answered Oct 10 '22 14:10

sharakan


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());
}    
like image 23
sfyumi Avatar answered Oct 10 '22 14:10

sfyumi