Skip to content

Commit

Permalink
!1170 MapUtil添加按固定大小划分Map的方法
Browse files Browse the repository at this point in the history
Merge pull request !1170 from 晨晨/v5-dev
  • Loading branch information
looly authored and gitee-org committed Feb 7, 2024
2 parents 016b6ef + f608d7d commit 56e7b1d
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -1519,4 +1519,30 @@ public static <K, V> V computeIfAbsentForJdk8(final Map<K, V> map, final K key,
}
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;
}
}

0 comments on commit 56e7b1d

Please sign in to comment.