I'm trying to break a list into a list of lists. In groovy I can easily do this:
def letters = 'a'..'g'
assert letters.collate(3) == [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]
Is there an equivalent in Java 8? I've looked into Collectors, but it seems a bit complicated. I really just want to group the items in the list into x.
A Collector is specified by four functions that work together to accumulate entries into a mutable result container, and optionally perform a final transform on the result. They are: creation of a new result container ( supplier() ) incorporating a new data element into a result container ( accumulator() )
Java Stream collect() is mostly used to collect the stream elements to a collection. It's a terminal operation. It takes care of synchronization when used with a parallel stream. The Collectors class provides a lot of Collector implementation to help us out.
Java 8 supports fluent APIs for pipeline stream operations. This is also supported in Groovy Collection operations. In Java a player variable that is specified for the Lambda, the Groovy closure doesn't need to specify a variable.
You may look into the Partition API for lists by Guava :
public static <T> java.util.List<java.util.List<T>> partition(java.util.List<T> list, int size)
Returns consecutive sublists of a list, each of the same size (the final list may be smaller).
How about this?
char start = 'a';
char last = 'g';
int n = 3;
List<Character> letters = IntStream.rangeClosed(start, last)
.mapToObj(it -> (char) it)
.collect(toList());
List<List<Character>> result = IntStream.range(0, (letters.size() + n - 1) / n)
.map(i -> i * n)
.mapToObj(i -> letters.subList(i, Math.min(i + n, letters.size())))
.collect(toList());
OR
List<List<Character>> result = IntStream.range(0, letters.size()).boxed().
collect(collectingAndThen(
groupingBy(i -> i / n, mapping(letters::get, toList())),
map -> new ArrayList<>(map.values())
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With