Java 8 – Function | Code Factory


Index Page : Link

Donate : Link

Medium Blog : Link

Applications : Link

  • Functions are exactly same as predicates except that functions can return any type of result but function should (can) return only one value and that value can be any type as per our requirement.
  • To implement functions oracle people introduced Function interface in 1.8v.
  • Function interface present in Java.util.function package.
  • Functional interface contains only one method i.e., apply()
@FunctionalInterface
public interface Function<T,R> {
    R apply(T t);
    default <V> Function<V,R> compose(Function<? super V,? extends T> before) { }
    default <V> Function<T,V> andThen(Function<? super R,? extends V> after) { }
   static <T> Function<T,T> identity() { }
}

Write a function to find length of given input string.

package com.codeFactory.function;

import java.util.function.Function;

public class Test {
	public static void main(String... args) {
		Function<String, Integer> f = s -> s.length();
		System.out.println(f.apply("Code"));
		System.out.println(f.apply("Factory"));
	}
}

Output :

4
7

Note : Function is a functional interface and hence it can refer Lambda Expression.

Differences between predicate and function :

PredicateFunction
To implement conditional checks we should go for predicateTo perform certain operation and to return some result we should go for function
Predicate can take one type parameter which represents input argument type.
Predicate<T>
Function can take 2 type parameters. First one represent input argument type and second one represent return Type. Function<T, R>
Predicate interface defines only one method called test()Function interface defines only one method called apply()
public boolean test(T t)public R apply(T t)
Predicate can return only boolean valueFunction can return any type of value

Note : Predicateis a boolean valued function and(), or(), negate() are default methods present inside Predicate interface

. . . . .

Program to remove spaces present in the given String by using Function :

package com.codeFactory.function;

import java.util.function.Function;

public class Test {
	public static void main(String... args) {
		String s = "Code Factory   .  .";
		Function<String, String> f = s1 -> s1.replace(" ", "");
		System.out.println(f.apply(s));
	}
}

Output :

CodeFactory..

. . . . .

Program to find Number of spaces present in the given String by using Function :

package com.codeFactory.function;

import java.util.function.Function;

public class Test {
	public static void main(String... args) {
		String s = "Code Factory   .  .";
		Function<String, Integer> f = s1 -> s1.length() - s1.replace(" ", "").length();
		System.out.println(f.apply(s));
	}
}

Output :

6

. . . . .

Program to find Student Grade by using Function :

package com.codeFactory.function;

import java.util.ArrayList;
import java.util.function.Function;

class Student {
	String name;
	int marks;
	Student(String name, int marks) {
		this.name = name;
		this.marks = marks;
	}
	
	@Override
	public String toString() {
		return "Student [name=" + name + ", marks=" + marks + "]";
	}
}

public class Test {
	public static void main(String... args) {
		ArrayList<Student> i = new ArrayList<Student>();
		populate(i);
		Function<Student, String> f = s -> {
			int marks = s.marks;
			if(marks >= 80) {
				return "A[Distinction]";
			} else if(marks >= 60) {
				return "B[First class]";
			} else if(marks >= 50) {
				return "C[Second class]";
			} else if(marks >= 35) {
				return "D[Third class]";
			} else {
				return "E[Failed]";
			}
		};
		for(Student s : i) {
			System.out.println(s + " -> " + f.apply(s));
		}
	}
	
	public static void populate(ArrayList<Student> i) {
		i.add(new Student("Narendra", 100));
		i.add(new Student("Amit", 65));
		i.add(new Student("Vijay", 55));
		i.add(new Student("Nitin", 45));
		i.add(new Student("Nahera", 25));
	}
}

Output :

Student [name=Narendra, marks=100] -> A[Distinction]
Student [name=Amit, marks=65] -> B[First class]
Student [name=Vijay, marks=55] -> C[Second class]
Student [name=Nitin, marks=45] -> D[Third class]
Student [name=Nahera, marks=25] -> E[Failed]

. . . . .

Progarm to perform Salary Increment for Employees by using Predicate & Function :

package com.codeFactory.function;

import java.util.ArrayList;
import java.util.function.Function;
import java.util.function.Predicate;

class Employee {
	String name;
	double salary;
	Employee(String name, double salary) {
		this.name = name;
		this.salary = salary;
	}
	
	@Override
	public String toString() {
		return "{name=" + name + ", salary=" + salary + "}";
	}
}

public class Test {
	public static void main(String... args) {
		ArrayList<Employee> i = new ArrayList<Employee>();
		populate(i);
		
		System.out.println("Before Increment :");
		System.out.println(i);
		
		Predicate<Employee> p = e -> e.salary < 4000;
		Function<Employee, Employee> f = e -> {
			e.salary += 500;
			return e;
		};
		
		ArrayList<Employee> i2 = new ArrayList<Employee>();
		for(Employee e : i) {
			if(p.test(e)) {
				i2.add(f.apply(e));
			}
		}
		
		System.out.println("After Increment :");
		System.out.println(i);
		
		System.out.println("Employees with incremented salary :");
		System.out.println(i2);
	}
	
	public static void populate(ArrayList<Employee> i) {
		i.add(new Employee("Narendra", 1000));
		i.add(new Employee("Amit", 2000));
		i.add(new Employee("Vijay", 3000));
		i.add(new Employee("Nitin", 4000));
		i.add(new Employee("Nahera", 5000));
		i.add(new Employee("Yogi", 10000));
	}
}

Output :

Before Increment :
[{name=Narendra, salary=1000.0}, {name=Amit, salary=2000.0}, {name=Vijay, salary=3000.0}, {name=Nitin, salary=4000.0}, {name=Nahera, salary=5000.0}, {name=Yogi, salary=10000.0}]
After Increment :
[{name=Narendra, salary=1500.0}, {name=Amit, salary=2500.0}, {name=Vijay, salary=3500.0}, {name=Nitin, salary=4000.0}, {name=Nahera, salary=5000.0}, {name=Yogi, salary=10000.0}]
Employees with incremented salary :
[{name=Narendra, salary=1500.0}, {name=Amit, salary=2500.0}, {name=Vijay, salary=3500.0}]

. . . . .

Function Chaining :

We can combine multiple functions together to form more complex functions. For this Function interface defines the following 2 default methods

  1. f1.andThen(f2) : First f1 will be applied and then for the result f2 will be applied
  2. f1.compose(f2) : First f2 will be applied and then for the result f1 will be applied
package com.codeFactory.function;

import java.util.function.Function;

public class Test {
	public static void main(String... args) {
		Function<String, String> f1 = s -> s.toUpperCase();
		Function<String, String> f2 = s -> s.substring(0, 4);
		
		System.out.println("f1 : " + f1.apply("Code"));
		System.out.println("f2 : " + f2.apply("Factory"));
		System.out.println("f1.andThen(f2) : " + f1.andThen(f2).apply("Code Factory"));
		System.out.println("f1.compose(f2) : " + f1.compose(f2).apply("Code Factory"));
	}
}

Output :

f1 : CODE
f2 : Fact
f1.andThen(f2) : CODE
f1.compose(f2) : CODE

Program to Demonstrate the difference between andThen() and compose() :

package com.codeFactory.function;

import java.util.function.Function;

public class Test {
	public static void main(String... args) {
		Function<Integer, Integer> f1 = i -> i+i;
		Function<Integer, Integer> f2 = i -> i*i*i;
		
		System.out.println("f1 : " + f1.apply(2));
		System.out.println("f2 : " + f2.apply(3));
		System.out.println("f1.andThen(f2) : " + f1.andThen(f2).apply(4));
		System.out.println("f1.compose(f2) : " + f1.compose(f2).apply(4));
	}
}

Output :

f1 : 4
f2 : 27
f1.andThen(f2) : 512
f1.compose(f2) : 128

. . . . .

Demo Program for User Authentication by using Function Chaining :

package com.codeFactory.function;

import java.util.Scanner;
import java.util.function.Function;

public class Test {
	public static void main(String... args) {
		Function<String, String> f1 = s -> s.toLowerCase();
		Function<String, String> f2 = s -> s.substring(0, 4);
		
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter user name :");
		String userName = sc.next();
		
		System.out.println("Enter password :");
		String psw = sc.next();
		
		if(f1.andThen(f2).apply(userName).equals("code") && psw.equals("code")) {
			System.out.println("Welcome Code Factory...");
		} else {
			System.out.println("Sorry...");
		}
				
	}
}

Output :

Enter user name :
CODE
Enter password :
code
Welcome Code Factory...


Enter user name :
Code132
Enter password :
code
Welcome Code Factory...


Enter user name :
132code
Enter password :
code
Sorry...

. . . . .

Function interface Static Method : identity()

Function interface contains a static method

static <T> Function<T, T> identity()

Returns a function that always returns its input argument

package com.codeFactory.function;

import java.util.function.Function;

public class Test {
	public static void main(String... args) {
		Function<String, String> f1 = Function.identity();
		String s = f1.apply("Code Factory");
		System.out.println(s);
	}
}

Output :

Code Factory

10 thoughts on “Java 8 – Function | Code Factory”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s