编写一段代码,实现将一个Map按元素数量分割成多个Map
时间: 2023-11-27 14:51:24 浏览: 46
以下是一个Java代码示例,它将一个Map对象按照指定的元素数量分割成多个Map对象:
```java
public static <K, V> List<Map<K, V>> splitMapBySize(Map<K, V> map, int size) {
List<Map<K, V>> maps = new ArrayList<>();
Map<K, V> subMap = new HashMap<>();
int count = 0;
for (Map.Entry<K, V> entry : map.entrySet()) {
subMap.put(entry.getKey(), entry.getValue());
count++;
if (count == size) {
maps.add(subMap);
subMap = new HashMap<>();
count = 0;
}
}
if (!subMap.isEmpty()) {
maps.add(subMap);
}
return maps;
}
```
使用示例:
```java
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map.put("d", 4);
map.put("e", 5);
map.put("f", 6);
List<Map<String, Integer>> maps = splitMapBySize(map, 2);
System.out.println(maps);
// Output: [{a=1, b=2}, {c=3, d=4}, {e=5, f=6}]
```