2个list集合,把其中一个平均分配给另一个,返回平均分配后的结果
时间: 2024-03-08 15:49:48 浏览: 23
如果你想要把一个 List 集合中的元素平均分配给另一个 List 集合,可以使用以下代码:
```java
public static <T> List<List<T>> distributeList(List<T> sourceList, List<T> destList){
int sourceSize = sourceList.size();
int destSize = destList.size();
int quotient = sourceSize / destSize;
int remainder = sourceSize % destSize;
int offset = 0;
List<List<T>> resultList = new ArrayList<>(destSize);
for (int i = 0; i < destSize; i++) {
int length = quotient + (remainder-- > 0 ? 1 : 0);
List<T> subList = new ArrayList<>(sourceList.subList(offset, offset + length));
subList.addAll(destList.subList(i, i + 1));
resultList.add(subList);
offset += length;
}
return resultList;
}
```
这个方法接受两个 List 集合作为参数,将第一个 List 集合中的元素平均分配到第二个 List 集合中,并返回平均分配后的结果,即一个 List 集合,其中每个元素都是一个 List 集合,包含了平均分配后的元素。如果第一个 List 集合的大小不能被第二个 List 集合的大小整除,则前 remainder 份集合将包含一个额外的元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)