Last active
May 30, 2016 08:32
-
-
Save timyates/8686020 to your computer and use it in GitHub Desktop.
Implementing Groovy's collate method in Java 8 Streams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
/* Efficiency must be questioned | |
* | |
* Also, no error checking, so could go infinite if called with dodgy params | |
* | |
* (left as an exercise for the reader) ;-) | |
*/ | |
public class Collate { | |
public <T> List<List<T>> collate( List<T> list, int size, int step ) { | |
return Stream.iterate( 0, i -> i + step ) | |
.limit( ( list.size() / step ) + 1 ) | |
.map( i -> list.stream() | |
.skip( i ) | |
.limit( size ) | |
.collect( Collectors.toList() ) ) | |
.filter( i -> !i.isEmpty() ) | |
.collect( Collectors.toList() ) ; | |
} | |
public static void main( String[] args ) { | |
Collate c = new Collate() ; | |
List<Integer> test = Arrays.asList( 1, 2, 3, 4, 5, 6, 7, 8, 9 ) ; | |
// Prints [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9], [9]] | |
System.out.println( c.collate( test, 3, 1 ) ) ; | |
// Prints [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9]] | |
System.out.println( c.collate( test, 3, 2 ) ) ; | |
// Prints [[1, 2, 3], [4, 5, 6], [7, 8, 9]] | |
System.out.println( c.collate( test, 3, 3 ) ) ; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Without
Math.min
,sublist
walks off the end of the list when you get near the end :-(Yeah, I think people have been asking for
java.util.Pair
for a long time