JAVA 8 Streams with examples | Stream API JAVA 8 | Tutorials - Scratcharound
First of all make it clear that this api has nothing to do with IO Streams in java just because of the similar names. Java 8 Stream Api is a part of java.util.stream package.
What is JAVA 8 Stream ?
Which means we can get a sequence of Objects from some source like Collection and perform different
sequential operations on each object. Also with the use of streams we can easily perform operations
in a parallel manner for a large Collection of objects which is even more efficient and time saving.
For parallel processing we use parallelStream which is an alternative of stream. We will
discuss parallelStream also later in this tutorial.
Example: Suppose we have a list of Student objects and we want to print the firstName of Student objects for which firstName starts with "J". Now if we use the old approach , we will have to do the iteration twice -
- First to filter the objects with firstName starting with "J".
- Second to Print the filtered content from the newly created list.
The code with the above old approach would look something like this - Code without Stream -
package com.scratcharound.tutorials.java8.streams;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class HelloStream {
public static void main(String [] args){
List<Student> students = Arrays.asList(
new Student("George","Thomas" ),
new Student("Jonney","Stuart" ),
new Student("Jackson","Ford" ),
new Student("Jack","Pit" ),
new Student("Ashley","Benson"));
List jStudents = new ArrayList<>();
// first iteration for filtering the list and creating a new list
for(Student s : students){
if(s.firstName.startsWith("J")){
jStudents.add(s);
}
}
// Second iteration for printing the newly created list
for(Student s : jStudents){
System.out.println(s.firstName);
}
}
}
What if we could do this entire task with just 3 lines of code and without creating a new ArrayList object.
Yes we can do this with the help of java 8 stream, see the code below -Code example with Stream
package com.ashu.java8.streams;
import java.util.Arrays;
import java.util.List;
public class HelloStream {
public static void main(String [] args){
List students = Arrays.asList(
new Student("George","Thomas" ),
new Student("Jonney","Stuart" ),
new Student("Jackson","Ford" ),
new Student("Jack","Pit" ),
new Student("Ashley","Benson"));
students.stream()
.filter(i-> i.firstName.startsWith("J"))
.forEach(i-> System.out.println(i.firstName));
}
}
Output :Jonney
Jackson
Jack
Note : For Using java 8 Streams, you must be familier with java 8
Lambda Expressions.In above example we have done the filtering and printing operations in only one iteration and that too without
creating a new ArrayList.
Code Explaination: In above code stream() is used for getting the stream (a sequential stream) from the
collection, like we obtain Iterator using .iterator() method. This has been provided for all the Collections in java 8.
filter(i-> i.firstName.startsWith("J")) , filters the stream and remove the elements for which the
condition defined in the filter is false. This method takes a
functional interface
Predicate as parameter
which has a abstract method test(T t) that return a boolean value. We have used lambda for this Predicate and
implemented the test(T t) method to return the true or false based on the condition provided.
Finally we have forEach(i-> System.out.println(i.firstName)) method which prints the firstName of the
remaining filtered objects from the stream.
- Java 8 Stream is not a in-memory data structure like collections, but data is computed on demand in Streams.
- Java Stream does not store data, but it performs the operations on data provided by some data source like collection in our case.
- As we have seen in our above example Stream uses functional interface and Lambda interface which makes it suitable for functional programming and writing sort lines of code.
- Java 8 Stream provides internal iterattion for Collections.
- We can also use parallel processiong for larger set of data, with the help of parallel stream.
Stream operations types -
Basically streams has two types of operations -1. Intermediate Operations
2. Terminal Operations
Intermediate Operations are operations which returns a stream after operation so that we can chain multiple intermediate operations without the termination.
As we can see in the example above filter() is an intermediate operation because it returns a filtered stream which we can use to perform further operations.
Terminal Operations are non-stream results, ie either they return a void or some other results which is not a stream. In our example above forEach() is a termination operation which returns void. We can use another termination operation count() on the intermediate stream which returns a long value, the count of stream after filter().
Long size = students.stream()
.filter(i-> i.getfName().startsWith("J"))
.count();
System.out.println(size);
As we have seen above, streams can be created using stream() and parallelStream() method, specially for collections. But we can create strema
without using .stream() method by just using of() method by providing a bunch of object references as argument.See the code given below -
Stream.of(new Student("George","Thomas" ),
new Student("Jonney","Stuart" ),
new Student("Jackson","Ford" ),
new Student("Jack","Pit" ),
new Student("Ashley","Benson")).filter(i-> i.firstName.startsWith("J"))
.forEach(i-> System.out.println(i.firstName));
Reusing a stream ?
We cannot reuse a stream after calling a termination operation. See code below for example -Streamstream = Stream.of(new Student("George","Thomas" ), new Student("Jonney","Stuart" ), new Student("Jackson","Ford" ), new Student("Jack","Pit" ), new Student("Ashley","Benson")).filter(i-> { System.out.println("Filter "+i.getfName()); return i.firstName.startsWith("J");}); stream.forEach(i-> System.out.println("for each "+i.firstName)); streamSupplier.count(); exception - Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed at java.util.stream.AbstractPipeline.evaluate(Unknown Source) at java.util.stream.ReferencePipeline.anyMatch(Unknown Source) at com.ashu.java8.streams.HelloStream.main(HelloStream.java:33)
above code will throw exception after executing count() termination operation.
To overcome this limitation we will have to create a new stream every time we want to call a termination operation.
This task can be done with the help of java.util.function.Supplier interface of java 8.
Supplier<Stream<Student>> streamSupplier = ()-> Stream.of(new Student("George","Thomas" ),
new Student("Jonney","Stuart" ),
new Student("Jackson","Ford" ),
new Student("Jack","Pit" ),
new Student("Ashley","Benson")).filter(i-> {
System.out.println("Filter "+i.getfName());
return i.firstName.startsWith("J");});
streamSupplier.get().forEach(i-> System.out.println("for each "+i.firstName));
System.out.println(streamSupplier.get().count());
In above example each time we call get() , it will create a new Stream on which we can call a termination operation.Java 8 - Lambda Expression with Examples
Java lambda expressions are the java's first step into functional programming like javascript and other functional programming languages.
Java before Lambda Expressions
We know very well that java is an object oriented language with an exception of primitives. Any function in java can not live on its own without belonging to some class. We always needed a class instance(object) to use a function in Java. We cannot define functions/methods which are independent so far. But now we have Labmda expressions to save us fro this problem, and solved the problem of functional programming for java.
What is Lambda Expression in java 8 ?
In simple words- Lambda expressions are the anonymous functions which can be created independently without belonging to any class. They can be passed as arguments,can be assigned to avariable and reduce the need of creating of anonymous class in java. Using lambda we can create a method in the same place where we are going to use it. Lmbda reduces the need of creating a method inside the class even if it is being used only once.
Example Without Lambda Expressions - Classsical Approach
Lets Try to uderstand the use of lambda expression wit a simple example -
Suppose we have an interface Readable with single abstract method read().
package com.tutorials.scratcharound.java8.lambda;
public interface Readable {
void read();
}
Now if we want to use the read() method , we have two options -1. Create a class which implements the Readable interface and provide the implementation of read method.
2. Create an anonymous class and provide the method implementation to use it.
Both the above approaches are old without the use of lambda expression -
package com.tutorials.scratcharound.java8.lambda;
public class Reader implements Readable {
@Override
public void read() {
System.out.println("Yes i can read");
}
}
Now create an instance of Reader and call the read method -
package com.tutorials.scratcharound.lambda;
public class HelloLambda {
public static void main(String args[]){
Readable reader = new Reader();
reader.read();
}
}
OR create an anonymous class to call the read() method -
package com.tutorials.scratcharound.java8.lambda;
public class HelloLambda {
public static void main(String args[]){
Readable reader = new Readable() {
@Override
public void read() {
System.out.println("Yes i also can read");
}
};
reader.read();
}
}
Example with Lambda Expressions
In both cases we will need to create a new object which is then used to call the read() method. But this same process can be done with much more ease by using java 8 Lambda Expressions.
package com.tutorials.scratcharound.java8.lambda;
public class HelloLambda {
public static void main(String args[]){
Readable reader = () -> System.out.println("I can Read With More Ease");
reader.read();
}
}
This part is lambda expression in the above example - () -> System.out.println("I can Read With More Ease"); In above example we have used Lambda Expression to declare the read() method without the need of creating any extra object.
How to write Lambda Expressions | Syntax
Lambda expressions are ususally written using the simple syntax -(arguments)->{body}
arguments are the arguments for that function
we can avoid curly braces if body of function contains single statement.
Some Examples -
//lambda with single parameter
(s) -> System.out.println(s);
//or could be written as
s -> System.out.println(s);
//lambda with no parameter
() -> System.out.println("I can Read With More Ease");
//lambda with more than one parameter
(a,b) -> System.out.println(a+b);
Example: Iterating ArrayList using lambda Expression -
package com.tutorials.scratcharound.java8.lambda;
import java.util.Arrays;
import java.util.List;
public class HelloLambda {
public static void main(String args[]){
List list = Arrays.asList(1,2,4,3,2,55,6);
list.stream().forEach(i->System.out.print(i));
}
}
In above example forEach method takes Consumer
functional interface as argument. And we have passed a
lambda exprssion as argument to it.Functional Interface with Lambda Expression -
We have already discussed details about functional interface in our previous articles.Click here to see details.In brief an interface having only one abstract method is called functional interface. Because functional interfaces have only one method, lambda expression can be easily assigned to the functional interface, as we have alredy seen in the above examples.
Readable is an functional interface, and we used the following code of line -
Readable reader = () -> System.out.println("I can Read With More Ease");
So here it was a a breif introduction about lmbda exprssions in java 8. We will learn more about some other features of lambda expression and new features of java 8.
Functional Interface in Java 8 | Java 8
Functional interfaces are introduced in java 8. Functional interfaces are also known as SAM Interface(single astract method interfaces). Functional interfaces help us in writing simpler and smaller code using lambda-expressions which is also introduced in java 8.
What is Functional interface in java 8 ?
'Any interface having exactly one abstract method is called functional interface'. Java 8 has also introduced an annotation @FunctionalInterface which can be used while declaring functional interfaces in java to avoid compile time errors. This annotation ensures that the interface annotated with @FunctionalInterface should qualify the conditions to be a functional interface, otherwise compiler will throw an error.
Example of functional interface -
package com.java8.interfaces;
@FunctionalInterface
public interface FunInterface {
void printName();
}
Above interface is a functional interface.Notice that, we can can always declare a functional interface without using the @FunctionalInterface annotation.
Adding default methods in functional interface -
We can add any number of default methods in functional interface and it still will be a functional interface, the reason is obvious that default methods are not abstract methods hence adding a default method does not increase the count of abstract methods in functional interface.For example -
package com.java8.interfaces;
@FunctionalInterface
public interface FunInterface {
void printName();
default boolean isFast(int speed){
return speed < 100 ? false : true;
}
default anotherMethod(){
//your code
}
}
Above interface is also a function interface with two default methods in addition to the abstract method.
What if we overrides Object class's public methods in functional interface ?
A functional interface can always override any public method from the Object class.It does not count as another abstract
method in the interface and it still will be a functional interface.
For example we can take 'Comparator' a predefined interface in java is a functional interface even though it overrides
the Object class method 'equals()' in addition to the abstract method of its own.
We also can create one of ours like 'Comparator' which overrides the 'Object' class's method.For Example -
package com.java8.interfaces;
@FunctionalInterface
public interface FunInterface {
void printName();
@Override
boolean equals(Object arg0);
@Override
String toString();
}
Above declared interface is still an functional interface, and we will not get any compilation error if we use
annotation @FunctionalInterface with it.So it was some detail about functional interface in java 8. In our next tutorial we will learn how to use java8 lambda expressions with functional interface. For any query, don't forget to comment below.
Java 8 interface Changes | New features in java 8 Interface | Static, Default Methods
Java 8 interfaces can now have method declarations also for default and static methods. Upto java 7 we can have only method declarations in java interfaces, but now in java 8 we can declare default and static methods as well in java interfaces.
In java writing interfaces has always been a challange because with time the number of classes implementing an interface increases and adding any new method in the interface causes a change to all the implementing classes. But now from java 8 we can have some default methods in java interfaces which we will not have to implement in the implementing classes.
Java 8 interface - Creating default method -
To create a default method we provide the keyword 'default' with method signature and obviously provides the body of the method. For example -
package com.tutorialsinn.java8.interfaces;
public interface InterfaceOne {
// method without body
void methodOne();
//default method with body
default void printColor(String color){
System.out.println("car color is " + color);
}
}
In above interface 'printColor(String color)' is a default method in interface 'InterfaceOne'. Now if any class implements this interface, it's
not mandatory for that class to implement tthis interface.
What if some class implements two Interfaces with same default method ?
Suppose we have another interface InterfaceTwo with same default method -
package com.tutorialsinn.java8.interfaces;
public interface InterfaceTwo {
//default method with body
default void printColor(String color){
System.out.println("cat color is " + color);
}
}
We know that java doesn't allow a class to extent more than one class because it would arise a diamond problem - means if
both the superclasses had same method then compiler won't be able to decide which superclass method to use for the subclass.
But we know that java allow us to implement any number of interfaces, in that case this diamond problem colud arise again
if the class implements both the interfaces having same default method. Well in that case, we will get a compile time error,
and it becomes mandatory for the class to override the default method.
So to avoid this kind of problem we will have to override the default method inside the class implementing the
interfaces.
package com.tutorialsinn.java8.interfaces;
public class Car implements InterfaceOne, InterfaceTwo{
String color;
String name;
int speed;
public Car(String color, String name, int speed) {
super();
this.color = color;
this.name = name;
this.speed = speed;
}
@Override
public void methodOne() {
}
@Override
public void printColor(String color) {
System.out.println("printed from inside the car class");
System.out.println("car color is " + color);
}
}
Notice that above class 'Car' has implemented both interfaces and hence overrides the common default method printColor(String color).Now if we call the default method it will execute the method we overrided in the 'Car' class, see code below -
package com.tutorialsinn.java8.interfaces;
public class RunCar {
public static void main(String[] args) {
Car car = new Car("White", "Ferrari", 250);
car.printColor(car.color);
}
}
The output of the above program will be -
printed from inside the car class car color is White
Java 8 Interface - static methods
We can use static methods also in java 8 interfaces, it's similar to default method except that any implementing class cannot override static methods. Static methods in Interfaces help us avoiding poor implementation of the static methods.To declare static method we use static keyword and provide method body. Interface static methods are not visible to the implementing class, so if we declare a method same as in interface in the implementing class then it's not method overriding. That's why if we try to put @override annotation on tha method in the implementing class we will get a compile time error. Static methods of java interfaces are only visible to the others methods of the same interface. Static methods can be directly called using the interface.Let's see a simple example of java 8 static methods in Interface-
let's create a simple static method 'isRunning' inside InterfaceOne, which is used another method of the same interface 'printSpeed';
package com.tutorialsinn.java8.interfaces;
public interface InterfaceOne {
void methodOne();
default void printColor(String color){
System.out.println("cat color is " + color);
}
static boolean isRunning(int speed){
return speed == 0 ? false : true;
}
default void printSpeed(int speed){
if(isRunning(speed)) System.out.println("car speed is "+speed);
else System.out.println("Car is not running");
}
}
Now let's try to use the above Interface's static method -
package com.tutorialsinn.java8.interfaces;
public class RunCar {
public static void main(String[] args) {
Car car = new Car("White", "Ferrari", 250);
car.printSpeed(car.speed);
}
}
Output - car speed is 250OR we can use this static method directly by Interface as utility method -
package com.tutorialsinn.java8.interfaces;
public class RunCar {
public static void main(String[] args) {
Car car = new Car("White", "Ferrari", 250);
if(InterfaceOne.isRunning(car.speed)){
System.out.println("car is running");
}
}
}
Output - car is runningSo, these were some points about java 8 interfaces. Hope you understood it and will use the same for your future coding. In addition of this functional interfaces are also added in java 8 which we will discuss in our next articles about java 8.