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 =
                  // perform some stream operations...
                  // collect into a list

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

you can using collectingAndThen as follows:

           // perform some stream operations...
           // 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.