Skip to content

Instantly share code, notes, and snippets.

@timyates
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timyates/9401832 to your computer and use it in GitHub Desktop.
Save timyates/9401832 to your computer and use it in GitHub Desktop.

In the current groovy-stream master branch (0.8), I'm adding Java support.

Say you have two lists, [1, 2, 3] and [4, 5, 6] and you want to print all the sums of these numbers that are odd.

You can now do this in Java 1.6+

Map<String,List<Integer>> map = new HashMap<String,List<Integer>>() {{
    put( "x", Arrays.asList( 1, 2, 3 ) ) ;
    put( "y", Arrays.asList( 4, 5, 6 ) ) ;
}} ;
Stream<Integer> s = Stream.from( map )
                          .map( new Function<Map<String, Integer>, Integer>() {
                              @Override
                              public Integer call( Map<String, Integer> map ) {
                                  return map.get( "x" ) + map.get( "y" );
                              }
                          } )
                          .filter( new Predicate<Integer>() {
                              @Override
                              public boolean call( Integer val ) {
                                  return val % 2 == 1;
                              }
                          } ) ;
for( Integer i : s ) {
    System.out.println( i );
}

And this (much nicer) in Java 8:

Map<String,List<Integer>> map = new HashMap<String,List<Integer>>() {{
    put( "x", Arrays.asList( 1, 2, 3 ) ) ;
    put( "y", Arrays.asList( 4, 5, 6 ) ) ;
}} ;
Stream.from( map )
      .map( e -> e.get( "x" ) + e.get( "y" ) )
      .filter( e -> e % 2 == 1 )
      .forEach( System.out::println ) ;

All of the naming and structure is currently up in the air, so may (and probably will) change.

Oh and btw, with Groovy, it's cleaner still (thanks to delegation, List and Map literals and boolean coercion)

Stream.from( x:[1,2,3], y:[4,5,6] )
      .map { x + y }
      .filter { it % 2 }
      .each { println it }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment