0% found this document useful (0 votes)
12 views16 pages

09 Lambdas

The document discusses lambdas and streams in Java. Lambdas are shorthand notations for anonymous functions, expressed as (parameters) -> {statements}. Streams represent sequences of generic items and provide functional programming capabilities. Common intermediate stream operations include filter, map, and sorted, while terminal operations include forEach, reduction, and search methods. Lambdas and streams enable a more declarative programming style in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views16 pages

09 Lambdas

The document discusses lambdas and streams in Java. Lambdas are shorthand notations for anonymous functions, expressed as (parameters) -> {statements}. Streams represent sequences of generic items and provide functional programming capabilities. Common intermediate stream operations include filter, map, and sorted, while terminal operations include forEach, reduction, and search methods. Lambdas and streams enable a more declarative programming style in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Lambdas and Streams

Dr. Fahed Jubair


Functional Programming
• Functional programming is a declarative programming paradigm that
relies on the evaluation of mathematical functions to express how a
series of inputs produces a series of outputs
• By contrast, imperative programming relies on explicit statements to
compute values
• Procedural programming and object-oriented programming are both imperative
programming models
• Below are two Wikipedia articles to help you understand better
https://en.wikipedia.org/wiki/Programming_paradigm
https://en.wikipedia.org/wiki/Comparison_of_multi-paradigm_programming_languages

© All rights reserved.


Functional Programming in Java

• Starting Java SE 8, lambdas and streams were introduced in Java to


provide more natural support for function programming

• In this lesion, we will cover an introductions to lambdas and streams

Note: the source for creating the slides for this lecture is chapter 17 in the book:
Java How to Program, Early Objects, 11 edition, Deitel and Deitel

© All rights reserved.


Lambda Expression
• In Java, a lambda expression is a shorthand notation for an anonymous function
• Lambdas are expressed in the form: {parameters} -> {statements}
• Examples:
(int x, int y) -> {return x+y;} // receive two inputs and return their sum
(x, y) -> {return x+y;} // types can be omitted and inferred from context by compiler
(x, y) -> x+y; // curly brackets and return keyword can be omitted if only a single statement inside
x -> System.out.println(x); // parenthesis can be removed if a single parameter is used

© All rights reserved.


Streams
• A stream represents a sequence of generic items

• In java, all streams are objects of type Java.util.stream.Stream

• Together, streams and lambda expressions enable functional


programming, i.e., performing operations on a sequence of items that is
stored inside arrays or collections

© All rights reserved.


The Stream<T> Interface
• A generalization of all stream objects in Java

• Methods in the Stream interface can be divides into three categories:


• Intermediate methods, which specify tasks to perform on the stream’s elements
and always result in a new stream
• Terminal methods, which initiate processing of a stream pipeline’s intermediate
operations and produce a result
• Static methods, which create new streams

© All rights reserved.


17.2 Functional Programming Technologies Overview 735

Intermediate Stream Operations


Intermediate Stream operations

filter Results in a stream containing only the elements that satisfy a condition.
distinct Results in a stream containing only the unique elements.
limit Results in a stream with the specified number of elements from the beginning
of the original stream.
map Results in a stream in which each element of the original stream is mapped to
a new value (possibly of a different type)—e.g., mapping numeric values to
the squares of the numeric values. The new stream has the same number of
elements as the original stream.
sorted Results in a stream in which the elements are in sorted order. The new stream
has the same number of elements as the original stream.

Fig. 17.3 | Common intermediate Stream operations.


© All rights reserved. Source: Java How to Program, Early Objects, 11 edition, Deitel and Deitel

Terminal Stream operations

forEach Performs processing on every element in a stream (e.g., display each element).
Reduction operations—Take all values in the stream and return a single value
elements as the original stream.
sorted Results in a stream in which the elements are in sorted order. The new stream
has the same number of elements as the original stream.

Fig. 17.3 | Common intermediate Stream operations.

Terminal Stream operations

forEach Performs processing on every element in a stream (e.g., display each element).
Reduction operations—Take all values in the stream and return a single value
average Calculates the average of the elements in a numeric stream. Terminal Stream
count
max
Returns the number of elements in the stream.
Locates the largest value in a numeric stream. Operations
min Locates the smallest value in a numeric stream.
reduce Reduces the elements of a collection to a single value using an associative accumu-
lation function (e.g., a lambda that adds two elements).
Mutable reduction operations—Create a container (such as a collection or StringBuilder)
collect Creates a new collection of elements containing the results of the stream’s prior
operations.
toArray Creates an array containing the results of the stream’s prior operations.
Search operations
findFirst Finds the first stream element based on the prior intermediate operations; immedi-
ately terminates processing of the stream pipeline once such an element is found.
findAny Finds any stream element based on the prior intermediate operations; immediately
terminates processing of the stream pipeline once such an element is found.
anyMatch Determines whether any stream elements match a specified condition; immedi-
ately terminates processing of the stream pipeline if an element matches.
allMatch Determines whether all of the elements in the stream match a specified condition.

Fig. 17.4 | Common terminal Stream operations. © All rights reserved. Source: Java How to Program, Early Objects, 11 edition, Deitel and Deitel

Stream in File Processing vs. Stream in Functional Programming


Throughout this chapter, we use the term stream in the context of functional program-
ming—this is not the same concept as the I/O streams we discussed in Chapter 15, Files,
+min(c: Comparator<? super T>): Optional<T> Returns the minimum element in this stream based on the comparator.
+findFirst(): Optional<T> Returns the first element from this stream.
+findAny(): Optional<T> Returns any element from this stream.
+allMatch(p: Predicate<? super T): boolean Returns true if all the elements in this stream match the predicate.
+anyMatch(p: Predicate<? super T): boolean Returns true if one element in this stream matches the predicate.
Terminal +noneMatch(p: Predicate<? super T): boolean Returns true if no element in this stream matches the predicate.
operations +forEach(action: Consumer<? super T>): void Performs an action for each element of this stream.

Optional<T> Static Stream Operations


+reduce(accumulator: BinaryOperator<T>): Reduces the elements in the stream to a value using the identity and an
associative accumulation function. Return an Optional describing the
reduced value.
.
+reduce(identity: T, accumulator: Reduces the elements in the stream to a value using the identity and an
BinaryOperator<T>): T associative accumulation function. Return the reduced value.
+collect(collector: <? super <T, A, R>>): R Performs a mutable reduction operation on the elements of this stream
using a Collector.
+toArray(): Object[] Returns an array consisting of the elements in this stream.
+empty(): Stream<T> Returns an empty sequential stream. (static method)
+of(values: T...): Stream<T> Returns a stream consisting of the specified values. (static method)
Static +of(values: T): Stream<T>
methods Returns a stream consisting of a single value. (static method)
+concat(a1: Stream<? extends T>, a2: Returns a lazily concatenated stream consisting of the elements in a1
Stream<? extends T>): Stream<T> followed by the elements in a2. (static method)

FIGURE 30.1 The Stream class defines the aggregate operations for the elements in a stream.

The methods are invoked using a stream pipeline. A stream pipeline consists of a source (e.g., stream pipeline
a list, a set, or an array), a method that creates a stream, zero or more intermediate methods,
and a final terminal method. The following is a stream pipeline example:
© All rights reserved. Source: Introduction to Java Programming, 10 edition, Y. Daniel Liang

Create a Zero or more One terminal


Source stream Intermediate methods method
Examples of Built-In Streams in Java
• IntStream interface
https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
• LongStream interface
https://docs.oracle.com/javase/8/docs/api/java/util/stream/LongStream.html
• DoubleStream interface
https://docs.oracle.com/javase/8/docs/api/java/util/stream/DoubleStream.html
• Arrays.stream method
https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#stream-T:A-
• Collections.stream method
https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#stream--

© All rights reserved.


Example 1

// output
content: 33 20 82 15 43 27
count is 6
max is 82
min is 15
sum is 220
average is 36.666666666666664
sum via reduce is 220
sum of squares is 11016
applying a filter: 20 15 27

© All rights reserved.


Example 2

// output
converting arr1 to integers:
13 32 36 94 15
converting arr3 to doubles:
1.1 2.2 3.3 4.4 5.5
printing the length of each word in arr3:
10 2 4 9 8

© All rights reserved.


Example 3

// output
strings: [java, compilers, c++, Discrete, compilers]
strings in uppercase: [JAVA, COMPILERS, C++, DISCRETE, COMPILERS]
strings in sorted order: [c++, compilers, compilers, Discrete, java]
strings in reverse sorted order: [java, Discrete, compilers, compilers, c++]
© All rights reserved.
Example 4

// output
[10, 13, 18, 14, 10, 15, 15, 18, 19, 13]
10 10 13 13 14 15 15
6
3.1622776601683795 3.605551275463989 4.242640687119285 3.7416573867739413 ……
© All rights reserved.
Classroom Exercise
• In a single line, use lambdas and streams to perform the below three tasks

© All rights reserved.


Home Exercise
• In a single line, use lambdas and streams to perform the below three tasks

© All rights reserved.

You might also like