Java 8: How to turn a list into a list of lists using lambda -




i'm trying split list list of list each list has maximum size of 4.

i know how possible using lambdas.

currently way i'm doing follow:

list<list<object>> listoflist = new arraylist<>();  final int max_row_length = 4; int startindex =0; while(startindex <= listtosplit.size() )     {     int endindex = ( ( startindex+max_row_length ) <  listtosplit.size() ) ? startindex+max_row_length : listtosplit.size();     listoflist.add(new arraylist<>(listtosplit.sublist(startindex, endindex)));     startindex = startindex+max_row_length; } 

update

it seems there isn't simple way use lambdas split lists. while of answers appreciated, they're wonderful example of when lambdas not simplify things.

try approach:

    static <t> list<list<t>> listsplitter(list<t> incoming, int size) {     // add validation if needed     return incoming.stream()             .collect(collector.of(                     arraylist::new,                     (accumulator, item) -> {                         if(accumulator.isempty()) {                             accumulator.add(new arraylist<>(singletonlist(item)));                         } else {                             list<t> last = accumulator.get(accumulator.size() - 1);                             if(last.size() == size) {                                 accumulator.add(new arraylist<>(singletonlist(item)));                             } else {                                 last.add(item);                             }                         }                     },                     (li1, li2) -> {                         li1.addall(li2);                         return li1;                     }             )); }      system.out.println(             listsplitter(                     arrays.aslist(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),                     4             )     ); 

also note code optimized, instead of:

new arraylist<>(collections.singletonlist(item)) 

use one:

list<list<t>> newlist = new arraylist<>(size); newlist.add(item); return newlist; 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -