Mar 8, 2014

Quick start with Scala for Java Developers

Let’s say we have number 1 to 100 in a list we will see how to perform different operations on this List in Java and Scala.

Add numbers 1 to 100 in a list
Java Way of doing it
Scala way of doing it
public static void main(String[] args) {
       List<Integer> list = new ArrayList<>();
       for(int i=0;i<=100;i++){
              list.add(i);
       }
}
val numbers = (1 to 100).toList


Get the sum of numbers
Java Way of doing it
Scala way of doing it
int sum = 0;
for (Integer num : list) {
       sum+=num;
}
System.out.println(sum);
println(numbers.foldLeft(0)((x,y)=>(x+y)))

Get the sum of even numbers
Java Way of doing it
Scala way of doing it
int sum = 0;
for (Integer num : list) {
       if(num%2==0){
              sum+=num;
       }
}
System.out.println(sum);
println(numbers.filter(_%2==0)
             .foldLeft(0)((x,y)=>(x+y)))

Get the sum of odd numbers that are greater than 15
Java Way of doing it
Scala way of doing it
int sum = 0;
for (Integer num : list) {
       if(num%2==1 && num>15){
              sum+=num;
       }
}
System.out.println(sum);
println(numbers.filter(x=>(x%2==1 && x>15))
             .foldLeft(0)((x,y)=>(x+y)))


From above examples we can see that by passing function to a list we can reduce the line of code that we need to write. This also have an advantage when code is running in multithreaded environment. I will keep adding similar examples for comparing Java and Scala in this tutorial.