Copyright 2018 All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechanical methods, without the prior written permission of the publisher, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. Table of Contents
Introduction
Lambdas exist in many coding languages. A Lambda is an anonymous function (function without a name) and is used to implement a function defined by a functional interface. Java8 introduces Lambdas into Java. Lambdas are Javas first steps into functional programming.
A Java Lambda expression is a function which can be created without belonging to any class. A Java Lambda expression can be passed around as if it was an object and executed on demand (which allows us to pass logic in a more compact way.) is the symbol that represents a Lambda.
1.1. Lambda syntax
1.1.1. General syntax
Lambda expressions introduce the arrow parameter into Java. It divides the lambda expression in two parts.
The left side specifies the parameters required by the expression which could also be empty if no parameters are required. The right side is the lambda body which specifies the actions of the lambda expression:
(parameter1, parameter2) -> {code of the function}
The example below is a Lambda with 2 parameters that prints those parameters to the console:
( int number, char character) -> {System.out.println(number); System.out.println(character); }
1.1.2. Abbreviations
- Parameters are optional in a Lambda
(number, character) -> {System.out.println(number); System.out.println(character); }
- A Lambda that has 1 parameter => the parentheses are optional
number -> {System.out.println(number); }
- A Lambda that hasnt any parameters => the parentheses are obliged
() -> {System.out.println(Hello World); }
- A Lambda that has only one instruction => the curly brackets are optional
number -> System.out.println(number);
- A Lambda that has only one instruction that is a return-instruction => the keyword return is optional
number -> number * number;
1.2 A Lambda is an implementation of a functional interface
A functional interface is an interface that contains one and only one abstract method. The Java standard Runnable interface is such a functional interface. It defines one method: run(). Aside from the built-in functional interfaces, we can create our own functional interfaces.
The example below is such a single method interface: public interface EvenNumber { boolean isEven( int number ); } In Java7 you would have to use an anonymous interface implementation like this: public class Main { public static void main(String[] args ) { EvenNumber myEvenNumber = new EvenNumber() { public boolean isEven( int number ) { return number % 2 == 0; }}; System. out .println( myEvenNumber .isEven(7)); } } In Java8 you can use a Lambda expression that implements the functional interface: public class Main { public static void main(String[] args ) { EvenNumber myEvenNumber = number -> number % 2 == 0; System. out .println( myEvenNumber .isEven(7)); } }
1.3 @Functional interface
All functional interfaces are recommended to have an informative @FunctionalInterfac e annotation. This not only clearly communicates the purpose of this interface, but also allows a compiler to generate an error if the annotated interface does not satisfy the conditions. An interface that has more than 1 abstract method is no longer a functional interface and cannot be implemented with a Lambda. @FunctionalInterface public interface EvenNumber { boolean isEven( int number ); }
Java standard library and lambdas
The interface comparator is a functional interface. @FunctionalInterface public interface EvenNumber { boolean isEven( int number ); }
Java standard library and lambdas
The interface comparator is a functional interface.
It has 1 abstract method: int compare(T object1 , T object2 ); you dont need to write a class to implement this interface, you can write a short lambda as implementation of the interface. class Main { public static void main(String[] args ) { String[] fruits = { "apple" , "cherries" , "banana" , "avocado" }; Arrays. sort ( fruits , ( fruit1 , fruit2 ) -> - fruit1 .compareTo( fruit2 )); System. out .println(Arrays. toString ( fruits )); }} You could also use the length of each word to sort the fruits. You just need to change the lambda expression to : fruit1.length() - fruit2.length( )
Stream and forEach
The interface Stream is new in Java8.
A stream represents a sequence of elements and supports different kinds of operations to perform computations upon those elements. Streams can be created from various data sources like an array, a list, a set, This guide teaches you how to work with Java 8 streams and how to use the different kinds of available stream operations like filter, map, reduce, The methods in the Stream interface accept a Lambda as parameter, which makes the code very short and readable.
3.1.1. foreach
forEach iterates over a collection and performs the given action for each element of the collection until all elements have been processed or the action throws an exception. The example below will print each fruit to the console: class Main { public static void main(String[] args ) { String[] fruits = { "apple" , "cherries" , "banana" , "avocado" }; Stream stream = Arrays. out .println( fruit )); }} It is possible to combine the last two instructions into one: class Main { public static void main(String[] args ) { String[] fruits = { "apple" , "cherries" , "banana" , "avocado" }; Arrays. stream ( fruits ) .forEach( fruit -> System. out .println( fruit )); }}
3.2 Date sources of a stream
3.2.1 List
A list can be a date source of a stream class Main { public static void main(String[] args ) { List fruits = Arrays. asList ( "apple" , "cherries" , "banana" , "avocado" ); fruits .stream() .forEach( fruit -> System. out .println( fruit )); }}
3.2.2 Set
A Set can be a date source of a stream class Main { public static void main(String[] args ) { Set numbers = new LinkedHashSet<>(); numbers .add(1); numbers .add(3); numbers .add(4); numbers .add(7); numbers .stream().forEach( getal -> System. out .println( getal )); }}
3.2.3 Map
The keySet, the values or the entrySet can be a date source of a stream. out .println( getal )); }}
3.2.3 Map
The keySet, the values or the entrySet can be a date source of a stream.
In the example below we use an entrySet. class Main { public static void main(String[] args ) { Map languages = new LinkedHashMap<>(); languages .put( "ENG" , "English" ); languages .put( "FRE" , "French" ); languages .entrySet().stream() .forEach( entry -> System. out .println( entry .getKey() + ':' + entry .getValue())); } }
3.3 String
A String can be a date source of a stream. The values in the stream are the characters of the String. class Main { public static void main(String[] args ) { "Lambdafun" .chars() .forEach( unicode ->System. out .println(( char ) unicode )); } }
3.4 Files
A file can be a date source of a stream.
The values in the stream are Strings that represent the lines in the file. class Main { private final static Path LANGUAGES_PATH = Paths. get ( "/data/languages.txt" ); public static void main(String[] args ) { try (Stream stream = Files. lines ( LANGUAGES_PATH )) { stream .forEach( line -> System. out .println( line )); } catch (IOException ex ) { ex .printStackTrace(); }}}
Next page