Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a Hashmap into two smaller maps

Tags:

java

I have one hashmap with K, V value of and that I want to split into two subMaps.

HashMap<Long,JSONObject>

One way is this I have found that we can use treemap and do subMapping.

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

But the thing is I am not getting subMap for jsonObject and I want to do it with HashMap only.

Thanks

like image 857
Akash Avatar asked Jan 28 '23 22:01

Akash


1 Answers

You can make use of the Java 8 Streaming API:

Map<Long, JSONObject> map = ...;
AtomicInteger counter = new AtomicInteger(0);
Map<Boolean, Map<Long, JSONObject>> collect = map.entrySet()
    .stream()
   .collect(Collectors.partitioningBy(
       e -> counter.getAndIncrement() < map.size() / 2, // this splits the map into 2 parts
       Collectors.toMap(
           Map.Entry::getKey, 
           Map.Entry::getValue
       )
   ));

This collects the map into 2 halfes, the first (map.get(true)) containing all the elements from below the middle and the second (map.get(false)) half containing all the elements from the middle upwards.

like image 142
Lino Avatar answered Jan 31 '23 07:01

Lino