Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Java 8 equivalent of the collate method in grails?

Tags:

java-8

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.

like image 331
beef Avatar asked Jun 15 '17 15:06

beef


People also ask

What is the use of collectors in Java 8?

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() )

What is collection stream in Java?

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.

Can we use stream API in Groovy?

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.


2 Answers

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).

like image 57
Mithun Sasidharan Avatar answered Nov 15 '22 08:11

Mithun Sasidharan


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())
          ));
like image 28
holi-java Avatar answered Nov 15 '22 09:11

holi-java