Java 8 streaming – or not?


One of the most advertised use cases of the new lambdas in Java 8 is the possibility to stream collections and transform it. The “series of tubes” has a lot of examples on how to do this, I just wanted to look at it from a different perspective, readability.

So starting with a real-life problem of a map Map<ResultKey, List> result which I want to transform into a Set<String>.

Before Java 8, I had something like:

Set<String> ids = new HashSet<> ();
for ( List<ResultEntry> list : result.values () ) {
  for ( ResultEntry entry : list ) {
    if ( entry.getAction () == Action.DELETE ) {
      String id = entry.getArtifact ().getId ();
      ids.add ( id );
    }
  }
}

Now, with Java 8, I can do:

Set<String> deleteSet = result.values ().stream ()
  .flatMap ( list -> list.stream () )
  .filter ( entry -> entry.getAction () == Action.DELETE )
  .map ( entry -> entry.getArtifact ().getId () )
  .collect ( Collectors.toSet () );
context.deleteArtifacts ( deleteSet );

Neither one is shorter nor seems less complex from an initial view. So, which one is better?