Functional interface:
interface Runnable { void run(); }
Runnable
interface is a very appropriate example as the only method present is the run method. Another Java “classic” example of functional interface is the Comparator<T> interface, in the following example is a before mentioned interface and the equals method inherited from Object, the interface is still functional as the compare method is the only abstract method, while the equals is inherited from the superclass.interface Comparator<T> {
boolean equals(Object obj);
int compare(T o1, T o2);
}
Stream
Stream
stream - according to [oxford dictionary], in computing it is a continuous flow of data or instructions, typically one having a constant or predictable rate.
Starting with JDK 8 stream represents a mechanism used for conveying elements from a data source, through a computational pipeline. A stream can use as data sources arrays, collections, generator functions, I/O channels.
Obtaining streams:
- From a
Collection
via thestream()
and/orparallelStream()
methods; - From an array via
Arrays.stream(Object[])
- From static factory methods on the stream classes, such as
Stream.of(Object[])
,IntStream.range(int, int)
orStream.iterate(Object, UnaryOperator)
; - The lines of a file can be obtained from
BufferedReader.lines();
- Streams of file paths can be obtained from methods in Files;
- Streams of random numbers can be obtained from
Random.ints();
- Numerous other stream-bearing methods in the JDK,
including BitSet.stream()
,Pattern.splitAsStream(java.lang.CharSequence)
, andJarFile.stream()
.
- filter – filters the stream based on the provided predicate
- map – creates a new stream by applying the mapping function to each element from the initial stream (corresponding methods for each numeric type: int, long, double)
- flatMap – operation that has the effect of applying a one-to-many transformation to the elements of the stream, and then flattening the results elements into a new stream. For example, if orders is a stream of purchase orders, and each purchase order contains a collection of line items, then the following produces a stream of line items:
orderStream.flatMap(order -> order.getLineItems().stream())
- distinct – returns a stream of distinct operations
- sorted – returns a stream of sorted operations
- peek – debug focused method that returns a stream consisting of elements of this stream, the provided action is performed on each element
list.stream()
.filter(filteringFunction)
.peek(e -> {System.out.println("Filtered value: " + e); });
.map(mappingFunction)
.peek(e -> {System.out.println("Mapped value: " + e); });
.collect(Collectors.intoList());
- limit – returns a truncated version of the current stream (no more than the limit number of elements)
- substream – returns a stream consisting of the remaining element starting from startposition, or between startPosition and endPosition
- forEach – applies the provided operation to every element of the stream. Also the forEachOrdered version exists
- toArray – extracts the elements of the stream into an array
- reduce – reduction method
- collect – mutable reduction method
- min – computes the minimum of the stream
- max – computes the maximum of the stream
- count – counts the elements of the stream
- anyMatch – returns true if there is an element matching the provided criteria
- allMatch – returns true if all the elements match
- noneMatch – returns true if none of the elements match
- findFirst – finds the first element that matches the provided condition
- findAny – returns an element from the stream
int sum = numbers.stream().reduce(0, (x,y) -> x + y);
int sum = numbers.stream().reduce(0, Integer::sum);
String concatenated = strings.reduce("", String::concat)
Lambda Related resources on +ManiSarkar‘s recommendation:
https://github.com/AdoptOpenJDK/lambda-tutorial
http://lambdafaq.com
Meta: this post is part of the Java Advent Calendar and is licensed under the Creative Commons 3.0 Attribution license. If you like it, please spread the word by sharing, tweeting, FB, G+ and so on!
Mani Sarkar December 7, 2013
Just did a hands-on session at @java2days in Sofia with the Bulgarian JUG (BGJUG) on #Lamdbas and we used these two sites as our reference: https://github.com/AdoptOpenJDK/lambda-tutorial and http://lambdafaq.com
Thanks to Olympiu for this article – will make use of it, useful stuff!
Olimpiu Pop December 8, 2013
This comment has been removed by the author.
Olimpiu Pop December 8, 2013
thank you Mani, I added the resource you point out in the useful resources part – I hope that's OK from your side.
Mani Sarkar December 12, 2013
My pleasure! Glad you added them, they are very helpful – people must repeatedly go through them – will make them thorough! Had great joy reading your post – very concise!