問(wèn)題描述
我想知道是否可以將 HashMap 拆分為更小的子圖.
I was wondering if it is possible to split a HashMap into smaller sub-maps.
在我的例子中,我有一個(gè) 100 個(gè)元素的 HashMap,我想從原始元素創(chuàng)建 2 個(gè)(或更多)更小的 HashMap,第一個(gè)包含 0 到 49 的條目,第二個(gè)包含 50 到 99 的條目.
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!
推薦答案
一定要用HashMap
嗎?
TreeMap
非常適合這種事情.這是一個(gè)示例(注意 0、50 和 99 是映射鍵,不是索引):
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);
這篇關(guān)于如何在 Java 中拆分 HashMap的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!