Tuesday, August 22, 2017

Imperative vs Functional programming, a simple example

Today a colleague was asking me the difference between functional and traditional programming in Java... I made a simple example to show how a FUNCTION can be used as a parameter, and the importance of Streams.... of course, in this example the traditional programming is much simpler and readable! Often functional programs can be really hard to decipher!


import java.util.Arrays;

public class HelloWorld
{
  static String[] theStrings = new String[] {"Pippo", "Pluto", "Paperino"};

  public static void main(String[] args) {
    theTraditionalWay();
    theFunctionalWay();  
  }

  static void theTraditionalWay() {
    for (int i = 0; i < theStrings.length; i++) System.out.println(theStrings[i].toUpperCase());
  }

  static void theFunctionalWay() {
    Arrays.stream(theStrings).map(String::toUpperCase).forEach(System.out::println);
  }
}

You can run it here https://www.compilejava.net/

No comments: