如果您无法使用值或键来确定分割位置,可以通过计算迭代次数来实现:
Map<Long, String> map = new HashMap<>();
Map<Long, String> sub1 = new HashMap<>();
Map<Long, String> sub2 = new HashMap<>();
int i = 0;
for(Map.Entry<Long, String> e : map.entrySet()){
(i++ % 2 == 0 ? sub1:sub2).put(e.getKey(), e.getValue());
}
我使用了三目运算符来增加计数器并选择地图。因此它将在这两个地图上平均分配值。
测试:
Map<Long, String> map = new HashMap<>();
map.put(1L, "foo");
map.put(2L, "bar");
map.put(3L, "for");
map.put(4L, "far");
Map<Long, String> sub1 = new HashMap<>();
Map<Long, String> sub2 = new HashMap<>();
int i = 0;
for(Map.Entry<Long, String> e : map.entrySet()){
(i++ % 2 == 0 ? sub1:sub2).put(e.getKey(), e.getValue());
}
System.out.println(sub1);
System.out.println(sub2);
{1=foo, 3=for}
{2=bar, 4=far}
如果需要,这将很容易适应分割为3、4或任意数量的地图:
public static void main(String[] args) {
Map<Long, String> map = new HashMap<>();
map.put(1L, "foo");
map.put(2L, "bar");
map.put(3L, "for");
map.put(4L, "far");
Map<Long, String> sub1 = new HashMap<>();
Map<Long, String> sub2 = new HashMap<>();
Map<Long, String> sub3 = new HashMap<>();
split(map, sub1, sub2, sub3);
System.out.println(sub1);
System.out.println(sub2);
System.out.println(sub3);
}
@SafeVarargs
public static <T, U> void split(Map<T,U> map, Map<T,U>... array){
int i = 0;
for(Map.Entry<T, U> e : map.entrySet()){
array[i++% array.length].put(e.getKey(), e.getValue());
}
}
{1=foo, 4=far}
{2=bar}
{3=for}
HashMap
的标准?由于它没有顺序,所以将其一分为二并不容易,因为“一半”未被定义。 - Linosorted.entrySet()
怎么样?遍历 HashMap 并将条目放入另外两个映射中。 - user1802604