本文介绍了将收藏拆分为Groovy中的子集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个包含未知数量项目的数组,我想将其分解为单独的数组,以便每个单独的数组包含不超过4个项目。在Groovy中执行此操作的最佳方式是什么?感谢! 我想出了这个: List.metaClass.partition = {size - > def rslt = delegate.inject([[]]){ret,elem - > (ret.last()} !rslt.last()? rslt [0 ..- 2]:rslt } def list = [1,2,3,4,5,6] .partition(4) 这应该给你: [[1,2,3,4],[5,6]] 更新! 使用Groovy 1.8.6+,您可以使用 list.collate(4)来获得相同的结果 p> I have an array containing an unknown number of items that I would like to split into separate arrays so that each separate array contains no more than 4 items. What is the best way to do this in Groovy? Thanks! 解决方案 We had this here: How to split a list into equal sized lists in Groovy?I came up with this:List.metaClass.partition = { size -> def rslt = delegate.inject( [ [] ] ) { ret, elem -> ( ret.last() << elem ).size() >= size ? ret << [] : ret } !rslt.last() ? rslt[ 0..-2 ] : rslt}def list = [1, 2, 3, 4, 5, 6].partition( 4 )Which should give you:[ [ 1, 2, 3, 4 ], [ 5, 6 ] ]Update!With Groovy 1.8.6+ you can use list.collate( 4 ) to get the same result 这篇关于将收藏拆分为Groovy中的子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-10 23:36