Saturday, December 24, 2016

An useful util to separate a list to multiple sublist in Java

Assume that you need to group/separate a List of object to multiple sublist with an specified size, below use should be useful.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.LinkedList;
import java.util.List;
 
public class CommonUtil {
    public static <T> List<List<T>> group(List<T> input, int bulkSize) {
        List<List<T>> result = new LinkedList<>();
        int from = 0;
        int to = bulkSize;
        int size = input.size();
 
        while (to < size) {
            result.add(input.subList(from, to));
            from = to;
            to += bulkSize;
        }
 
        if (from < size) {
            result.add(input.subList(from, size));
        }
        return result;
    }
 
}

No comments :

Post a Comment