MapUtil添加按固定大小划分Map的方法

Signed-off-by: 晨晨 <2050365570a@gmail.com>
This commit is contained in:
晨晨 2024-02-04 09:11:13 +00:00 committed by Gitee
parent 016b6ef810
commit f608d7de24
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F

View File

@ -1519,4 +1519,30 @@ public class MapUtil {
} }
return value; return value;
} }
/**
* 将一个Map按照固定大小拆分成多个子Map
*
* @param map Map
* @param size 子Map的大小
* @return 子Map列表
*/
public static <K, V> List<Map<K, V>> partition(Map<K, V> map, int size) {
if (map == null) {
throw new NullPointerException("Map must not be null");
} else if (size <= 0) {
throw new IllegalArgumentException("Size must be greater than 0");
}
List<Map<K, V>> list = new ArrayList<>();
Iterator<Map.Entry<K, V>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map<K, V> subMap = new HashMap<>(size);
for (int i = 0; i < size && iterator.hasNext(); i++) {
Map.Entry<K, V> entry = iterator.next();
subMap.put(entry.getKey(), entry.getValue());
}
list.add(subMap);
}
return list;
}
} }