Sunday, April 17, 2016

Java 8 Streams API: Immutable List Collector

Instead of first collecting a stream into a list and then making it unmodifiable, as shown below:

mutableList = list.stream()
                  // perform some stream operations...
                  .filter(myFilterPredicate)
                  .map(myMapperFunction)
                  // collect into a list
                  .collect(toList());

// now make the list unmodifiable
return Collections.unmodifiableList(list);

you can using collectingAndThen as follows:

return list.stream()
           // perform some stream operations...
           .filter(myFilterPredicate)
           .map(myMapperFunction)
           // collect into an unmodifiable list
           .collect(collectingAndThen(toList(), Collections::unmodifiableList));

1 comment:

  1. Great post dear. It definitely has increased my knowledge on Spark. Please keep sharing similar write ups of yours. You can check this too for Spark tutrial as i have recorded this recently on Spark. and i'm sure it will be helpful to you.https://www.youtube.com/watch?v=8Kcu63H0d8c

    ReplyDelete