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
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.
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