Efficient way to divide a list into lists of n size

前端 未结 14 1315
无人共我
无人共我 2020-11-27 16:59

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

implemented with Array

14条回答
  •  广开言路
    2020-11-27 17:16

    Well i wrote one myself before i saw ColinD's answer (+1) and using Guava is definitely the way to go. It was too much fun to leave alone and so the below gives you a copy of the list rather than views so GUava's is definitely more efficient than this. I'm posting this because it was fun to write rather than suggesting it is as efficient:

    The Hamcrest test (one of anyway):

    assertThat(chunk(asList("a", "b", "c", "d", "e"), 2), 
               equalTo(asList(asList("a", "b"), asList("c", "d"), asList("e"))));
    

    The code:

    public static  Iterable> chunk(Iterable in, int size) {
        List> lists = new ArrayList();
        Iterator i = in.iterator();
        while (i.hasNext()) {
            List list = new ArrayList();
            for (int j=0; i.hasNext() && j

提交回复
热议问题