Last Updated: March 08, 2016
·
1.12K
· raulraja

Scala Vs Java Collection filter

One of the nicest scala features is for comprehension loops. They allow you to express the expected outcome of the loop and manipulate Seq, List and other collections in a way that saves time and removes clutter from its Java counterpart.

Consider the following…

JAVA

List<Integer> even = new ArrayList<Integer>();
for (String num : strings) {
 int parsedInt = Integer.parseInt(num);
 if (parsedInt % 2 == 0) {
  ints.add(parsedInt);
 }
} 

Scala

val ints = for (num <- strings; if num.toInt % 2 == 0) yield num.toInt

or even easier

val ints = strings map { _.toInt } filter {_ % 2 == 0}