[英]Divide array list into sub list of fixed size
我有一个数组列表,我想将其分成固定大小的子列表,例如-
如果我的列表大小是100,我想在一个列表中包含30个元素,那么基本上我想创建4个子列表。实现此目的的最优化方法是什么...我在互联网上看了很多建议导致将数组列表分解为没有固定大小的生存列表。任何Leads.pointers都受到高度赞赏。 最可取的是,我想要一种可以完成这项工作的服务/方法
如果允许您使用第三方库,则Guava 会将其作为单一方法Lists.partition提供 ,这是一个恒定时间视图。
public static <T> List<List<T>> split( List<T> alist, int len ){
List<List<T>> listOfLists = new ArrayList<>();
int hi = 0;
for( int lo = 0; lo < alist.size(); lo = hi ){
hi = lo + len;
if( hi > alist.size() ) hi = alist.size();
listOfLists.add( new ArrayList<T>( alist.subList( lo, hi ) ) );
}
return listOfLists;
}
List<E> subList(int fromIndex, int toIndex);
产生子清单。 <T> T[] toArray(T[] a);
将每个subList转换为数组<T> T[] toArray(T[] a);
Arrays.asList
将为您提供该数组支持的固定大小的列表。 我喜欢@laune的答案,但是如果您使用Java 8,也可以使用此功能样式方法来避免外部循环。
public static <T> List<List<T>> splitJava8(List<T> alist, final int len) {
return IntStream.range(0, alist.size()) // Iterate over the whole thing
.filter(i -> i % len == 0) // Filter out every 'len' number
.boxed() // Create a stream (instead of IntStream)
.map(i -> alist.subList(i, Math.min(i + len, alist.size()))) // create sublists
.collect(Collectors.toList()); // Collect the whole thing to a list of lists
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.