在Grails中是否有Java 8等效的collate方法? [英] Is there a Java 8 equivalent of the collate method in grails?
本文介绍了在Grails中是否有Java 8等效的collate方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将列表分成列表列表。在groovy中,我可以很容易地做到这一点:
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']]
Java 8中是否存在等价物?我看过收藏家,但看起来有点复杂。我真的只想将列表中的项目分组为x。
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.
推荐答案
这个怎么样?
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())
));
这篇关于在Grails中是否有Java 8等效的collate方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文