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}
Written by Raúl Raja
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Scala
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#