Friday, September 01, 2017

Pipeline operations - Scala v/s Java

In both Java & Scala, the pipeline operations are functional and do not modify the original collection.

In the below examples in the case of Java, the pipeline operations are working on streams which are evaluated lazily. 

Intermediate operations like map/filter do not actually execute immediately but just create a new stream which when traversed give the mapped/filtered output of the source stream.

Terminal operations like reduce/forEach cause the stream to be traversed to produce a result or side-effect.

In the below examples for Scala, the pipeline operations are operating on plain collections and hence execute eagerly unlike in the case of Java. However, in Scala, there are ways to run pipeline operations on streams.

(1) Foreach

Java

List<String> fruits = Arrays.asList("pear", "apple", "strawberry", "mango", "banana", "orange")
fruits.forEach(System.out::println)

Scala

val fruits = List("pear", "apple", "strawberry", "mango", "banana", "orange")
fruits.foreach(println)


(2) Map

Java

List<String> ufruits = fruits.stream().map(s -> s.toUpperCase()).collect(Collectors.toList())

or

List<String> ufruits = fruits.stream().map(String::toUpperCase).collect(Collectors.toList())

Scala

val ufruits = fruits.map(_.toUpperCase)


(3) Reduce

Java

Optional<String> allfruits = fruits.stream().reduce((s1,s2) -> s1 + "-" + s2)

Scala

val ufruits = fruits.reduce(_ + "-" + _)


(4) Filter

Java

List<String> selected = fruits.stream().filter(s -> s.startsWith("a")).collect(Collectors.toList())


Scala

val ufruits = fruits.filter(_.startsWith("a"))

No comments: