Showing posts with label functional. Show all posts
Showing posts with label functional. Show all posts

Tuesday, December 31, 2019

Functional Interfaces

The Supplier interface is a generic functional interface with a single method that has no arguments and returns a value of a parameterized type.

The Consumer functional interface. Its single method takes a parameter and returns void.

The Function represents a function that accepts one argument and produces a result.



BiFunction represents a function that accepts two arguments and produces a result. This is the two-arity specialization of Function.


BinaryOperator Represents an operation upon two operands of the same type, producing a result of the same type as the operands.


(freely extracted from https://www.baeldung.com/java-completablefuture

and from https://www.baeldung.com/java-bifunction-interface


)




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/