有效的方式来划分列表成n大小的列表 [英] Efficient way to divide a list into lists of n size

查看:108
本文介绍了有效的方式来划分列表成n大小的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,我要划分成N大小的小数组,并在每个执行操作。
我现在这样做的方法是

I have an array, which I want to divide into smaller arrays of n size, and perform an operation on each. My current method of doing this is

在Java中的ArrayList实现的(任何伪code会做)

implemented with ArrayLists in Java (any pseudocode will do)

    for (int i = 1; i <= Math.floor((A.size() / n)); i++) {
            ArrayList temp = subArray(A, ((i * n) - n),
                    (i * n) - 1);
            // do stuff with temp
        }

    private ArrayList<Comparable> subArray(ArrayList A, int start,
                int end) {
            ArrayList toReturn = new ArrayList();
            for (int i = start; i <= end; i++) {
                toReturn.add(A.get(i));
            }
            return toReturn;
        }

其中A是该列表中,n是所希望的列表的大小

where A is the list, n is the size of the desired lists

我相信(在规模达100万)与相当大名单的工作,所以我试图找出什么是更有效时,这种方式花费过多时间。

I believe this way is taking too much time when working with considerably large lists (of up to 1 million in size) so I'm trying to figure out what would be more efficient.

推荐答案

您会希望做一些让使用<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/List.html#subList%28int,%20int%29\">List.subList(int, INT)的意见,而不是复制的每个子列表。要做到这一点其实很容易,使用番石榴的<一个href=\"http://guava-libraries.google$c$c.com/svn/tags/release09/javadoc/com/google/common/collect/Lists.html#partition%28java.util.List,%20int%29\">Lists.partition(List, INT)方式:

You'll want to do something that makes use of List.subList(int, int) views rather than copying each sublist. To do this really easily, use Guava's Lists.partition(List, int) method:

List<Foo> foos = ...
for (List<Foo> partition : Lists.partition(foos, n)) {
  // do something with partition
}

请注意,这像很多事情,是不是很有效,以列表不是 RandomAccess的 (如的LinkedList )。

Note that this, like many things, isn't very efficient with a List that isn't RandomAccess (such as a LinkedList).

这篇关于有效的方式来划分列表成n大小的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆