JAVA FEATURES
LAMBDA EXPRESSIONS
A Lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar
To methods , but they do not need a name and they can be implemented right in the body of a method . The simplest
Expression contains a single parameter and an expression : parameter-> expression
EXAMPLE
Use a Lambda expression in the ArrayList’s forEach() method to print every item in the list :
Method
A method reference is a collection of statements that perform some specific task and return the result to the caller. A
Reference
method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping
the code. In this article, we will see how to use methods as value.
In Java8 we can use the method as if they were objects or primitive values, and we can treat them as a variable. The
example shows the function as a variable in java:
// This square function is a variable getSquare.
Function<Integer, Integer> getSquare = i -> i * i;
// Pass function as a argument to other function easily
SomeFunction(a, b, getSquare);
Sometimes, a lambda expression only calls an existing method. In those cases, it looks clear to refer to the existing
method by name. The method references can do this, they are compact, easy-to-read as compared to lambda expression.
A method reference is the shorthand syntax for a lambda expression that contains just one method call. Here’s the
general syntax of a method reference:
// To refer a method in an object
Object :: methodName
The method references can only be used to replace a single method of the lambda expression. A code is more clear and
short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather
than using a single function lambda expression to achieve the same. In general, one doesn’t have to pass arguments to
method references.
The following example is about performing some operation on elements in the list and add them.
Java
public int tranformAndAdd(List<Integer> l,
Function<Integer, Integer> ops)
{
int result = 0;
for (Integer s : l)
result += f.apply(s);
return results;
}
// Operations utility class
class OpsUtil {
// Function for half the variable
public static Integer doHalf(Integer x)
{
return x / 2;
}
// Square
public static Integer doSquare(Integer x)
{
return x * x;
}
}
Functional
Interface
❖ A functional interface is an interface that contains only one abstract method.
❖ They can have only one functionality to exhibit. Lambda expressions can be used to represent the instance of a
❖ functional interface.
❖ A functional interface can have any number of default methods. Runnable, ActionListener, Comparable are some of
❖ the examples of functional interfaces.
// Java program to demonstrate functional interface
class Test
{
public static void main(String args[])
{
// create anonymous inner class object
new Thread(new Runnable()
{
@Override
public void run()
{
System.out.println("New thread created");
}
}).start();
}
}
Streams
► A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
► A streams pipeline consists of a source, followed by zero or more intermediate operations, and a terminal operation.
Source Filter Sort Map Collect
► Stream source can be created from Collections, Lists, Sets, ints, longs, doubles, arrays, lines of a file.
► Stream operations can either be intermediate operations or terminal operations:
❖ Intermediate Operations such as filter, map and sort return a stream so that we can chain multiple intermediate operations(zero
or more intermediate operations are allowed).
❖ Order matters for large datasets: filterfirst, then sort or map.
❖ For very large datasets use Parrallelstream to enable multiple threads.
❖ Intermediate operations include:
❖ anyMatch() Flatmap()
❖ Map() Distinct()
❖ Filter() Skip()
❖ Sorted () Findfirst()
o Terminal Operations such as forEach, collect, or reduce are either void or return a non-stream result.
❖ one terminal operation is allowed
❖ forEach applies the same function to each element
❖ Collect saves the elements into a collection
❖ Other options reduce the stream to a single summary element
❖ terminal operations include:
❖ Count()
❖ Max()
❖ Min()
❖ Reduce()
❖ Summarystatistics9)
Advantages of Streams
► Will make you a more efficient java programmer
► Make heavy use of lambda expressions
► Parrallel streams make it very easy to multi thread operations
Below is a series of examples of how strings work and some of the different features and functions that streams have:
import java.util.Arrays;
import java.util.List;
import java.util.stream.*;
import java.util.*;
import java.nio.file.*;
import java.io.IOException;
public class JavaStreams {
public static void main(String[] args) throws IOException {
// 1. Integer Stream
IntStream
.range(1, 10)
.forEach(System.out::print);
System.out.println();
// 2. Integer Stream with skip
IntStream
.range(1, 10)
.skip(5)
.forEach(x -> System.out.println(x));
System.out.println();
// 3. Integer Stream with sum
System.out.println(
IntStream
.range(1, 5)
.sum());
System.out.println();
// 4. Stream.of, sorted and findFirst
Stream.of("Ava", "Aneri", "Alberto")
.sorted()
.findFirst()
.ifPresent(System.out::println);
// 5. Stream from Array, sort, filter and print
String[] names = {"Al", "Ankit", "Kushal", "Brent", "Sarika", "amanda", "Hans", "Shivika", "Sarah"};
Arrays.stream(names) // same as Stream.of(names)
.filter(x -> x.startsWith("S"))
.sorted()
.forEach(System.out::println);
// 6. average of squares of an int array
Arrays.stream(new int[] {2, 4, 6, 8, 10})
.map(x -> x * x)
.average()
.ifPresent(System.out::println);
// 7. Stream from List, filter and print
List<String> people = Arrays.asList("Al", "Ankit", "Brent", "Sarika", "amanda", "Hans", "Shivika", "Sarah");
people
.stream()
.map(String::toLowerCase)
.filter(x -> x.startsWith("a"))
.forEach(System.out::println);
// 8. Stream rows from text file, sort, filter, and print
Stream<String> bands = Files.lines(Paths.get("bands.txt"));
bands
.sorted()
.filter(x -> x.length() > 13)
.forEach(System.out::println);
bands.close();
// 9. Stream rows from text file and save to List
List<String> bands2 = Files.lines(Paths.get("bands.txt"))
.filter(x -> x.contains("jit"))
.collect(Collectors.toList());
bands2.forEach(x -> System.out.println(x));
// 10. Stream rows from CSV file and count
Stream<String> rows1 = Files.lines(Paths.get("data.txt"));
int rowCount = (int)rows1
.map(x -> x.split(","))
.filter(x -> x.length == 3)
.count();
System.out.println(rowCount + " rows.");
rows1.close();
collectors
Java Collectors
❖ Collectors is a final class that extends Object class. It provides reduction operations, such as accumulating
elements into collections, summarizing elements according to various criteria, etc.
❖ They are used to collect elements of stream into collection as they act as a bridge between stream and
collection which can be used to convert stream into different types of collections e.g. map and set.
❖ They do also provide functionalities to join string , group by and many other reduction operators so as to
return a meaningful result.
❖ It is often used with collect () method of stream class which however accepts a Collectors.
❖ Collectors they do provides converting stream to different collection, grouping, joining and counting
methods.
Examples of collectors
a) Collectors to Set()
❖ This is a method that is used to collect the result of a Stream into Set.
❖ It can also be used to convert a stream to set.
❖ The sets that are to be returned by this method are not guaranteed to be a HashSet or being
LinkedHashSet.
❖ They can only be a sample implementation of the Set interface.
❖ One the drawbacks of collectors to set() is that they do not provide ordering guarantee hence on is
likely to lose the order of the elements available in the stream.
b.) Collectors.toList()
❖ This is a method of java.util.stream.Collectors class that is used for collecting elements into a list.
❖ This can only be used if one knows that their stream contains duplicates and wants to retain them .
❖ It also preserves the order in which the elements are present in Stream.
Collectors examples cont.……
c.) Collectors.toCollection()
❖ This is a method that is used to convert a stream into collection class such as ArrayList , vector etc
❖ It also accepts a supplier and one can provide a constructor reference for the class they want to use to collect elements
to stream.
d.) Collectors.toMap()
❖ This method also provides a utility method to create a map from the elements of stream.
❖ Whilst converting stream to map one has make sure that the stream does not have a duplicate since map doesn’t allow
duplicate keys.
❖ These duplicates can be removed from stream using distinct{ } methods.
d.) Collectors. Joining ()
❖ This method can be used to join all elements of the stream into single stream where parts are separated by a delimiter.
❖ Example if an individual wants to create a long , separated comma string from all the elements of stream then it can be
done by making use of the collectors.joining() methods .
Advantages of collectors
❖ It reduces programming efforts by providing useful data structures and algorithms.
❖ It increases programming speed an quality
❖ Fosters software reuse as the new data structures that conform to the standard collection interfaces
can be reused.
disadvantages of collectors
❖ It can not be done compile time type checking.
❖ It must cast to correct type.
Examples of programs that we designed
which used collectors
These programs they do have comments within