Java 8
Java 8
Java 8
Note: When we have single line in body then curly braces are optional
( ) -> s.o.p ("hi");
Ex:-2
s.o.p(a+b);
Ex:-3
return name.length ( );
Supplier -
Supplier is a predefined functional interface introduced in java 1.8v
It contains only one abstract method that is get ( ) method
Supplier interface will not take any input, it will only returns the
value.
Example :
@FunctionalInterface
interface MyInterface {
publicvoid m1();
}
public class MethodRef {
public static void m2() {
System.out.println("This is m2( ) method");
}
public static void main(String[] args) {
MyInterface mi = MethodRef::m2;
mi.m1();
}}
//Doctor class creating object
Supplier<Doctor> s = Doctor::new;
System.out.println(doctor.hashCode());
}}
class Doctor {
public Doctor() {
System.out.println("Doctor constructor....");
}}
Stream api
Stream API introduced in java 1.8v
Stream API is used to process the data
Note: Collections are used to store the data
Stream API is one of the major features added in java 1.8v
Stream in java can be defined as sequence of elements that comes from
a source.
Source of data for the Stream can be array or collection.
Few Important Points About Streams
Stream is not a data structure. Stream means bunch of operations
applied on source data. Source can be collection or array.
Stream will not change original data structure of the source (It will just
process the data given by the source.
Stream Creation
In Java we can create Stream in 2 ways
1) Stream.of (e1, e2, e3, e4.....)
2) stream ( ) method
Stream Operations
Stream API provided several methods to perform Operations on the data
We can divide Stream api methods into 2 types
1) Intermediate Operational Methods
2) TerminalOperational Methods
Intermediate Operational methods will perform operations on the
stream and returns a new Stream
Ex: filter ( ) , map ( ) etc....
TerminalOperational methods will take input and will provide result as
output.
Ex: count ( )
Filtering with Streams
Filtering means getting required data from original data
Ex: get only even numbers from given numbers
Ex: get emps whose salary is >= 1,00,000
Ex: Get Mobiles whose price is <= 15,000
To apply filter on the data, Stream api provided filter ( ) method
Ex : Stream filter (Predicate p)
Example - 1 : Filter
package in.ashokit.streams;
importjava.util.Arrays;
importjava.util.List;
public class FirstDemo {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(66, 32, 45, 12, 20);
/*for (Integer i : list) {
if (i > 20) {
System.out.println(i);
} }*/
/* Stream<Integer> stream = list.stream();
Stream<Integer>filteredStrem = stream.filter(i -> i > 20);
filteredStrem.forEach(i -> System.out.println(i)); */
list.stream().filter(i -> i > 20).forEach(i -> System.out.println(i));
}}
Mapping Operations
Mapping operations are belongs to intermediate operations in the Stream api
Mapping operations are used to transform the stream elements and return transformed
elements as new Stream
Ex : Stream map (Function function) ;
public class FirstDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("india","usa","uk", "japan");
/*for(String name : names) {
System.out.println(name.toUpperCase());
}*/
names.stream().map(name -> name.toUpperCase()).forEach(n -> System.out.println(n));
names.stream().mapToInt(name -> name.length()).forEach(i -> System.out.println(i));
}}
Example-2 : map ( ) method
public class FirstDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ashok", "Anil", "Raju", "Rani", "John", "Akash", "Charles");
// print name with its length which are starting with 'A' using Stream API
//Ashok - 5
//Anil - 4
//Akash - 5
names.stream()
.filter(name -> name.startsWith("A"))
.map(name -> name + "-" +name.length())
.forEach(name -> System.out.println(name));
}
}
Collectors with Stream
Collectors are used to collect data from Stream.
Example :
class Person {
String name;
String country;
public Person(String name, String country) {
this.name = name;
this.country = country;
}
@Override
public StringtoString() {
return "Person [name=" + name + ", country=" + country + "]";
}}
package in.asit.streams;
importjava.util.Arrays;
importjava.util.List;
importjava.util.stream.Collectors;
public class FirstDemo {
public static void main(String[] args) {
Person p1 = new Person("John", "USA");
Person p2 = new Person("Steve", "JAPAN");
Person p3 = new Person("Ashok", "INDIA");
Person p4 = new Person("Ching", "CHINA");
Person p5 = new Person("Kumar", "INDIA");
List<Person> persons = Arrays.asList(p1, p2, p3, p4, p5);
List<Person> indians = persons.stream() .filter(p -> p.country.equals("INDIA"))
.collect(Collectors.toList());
indians.forEach(i -> System.out.println(i));
}}
List<Person> persons = Arrays.asList(p1, p2, p3, p4, p5);
// collect names of persons who are belongs to india and store into
names collection
List<String> names = persons.stream()
.filter(p -> p.country.equals("INDIA"))
.map(p -> p.name)
.collect(Collectors.toList());
System.out.println(names);
Set - 1 : Intermediate Operations (will return Stream)
Filters ----> filter ( )
Mappings ----> map ( ) & flatMap ( )
Slicing ----> distinct ( ) & limit () & skip ( )
LocalDateTime current = LocalDateTime.now(); // will give us the current time and date
System.out.println("current date and time : "+ current);
In java 1.8 versions, new classes got introduced to deal with Date &
Time functionalities
1) java.time.LocalDate (it will deal with only date)
2) java.time.LocalTime (it will deal with only time) 3)
java.time.LocalDateTime (it will deal with both date & time)
forEach (Consumer c) method
forEach (Consumer c) method introduced in java 1.8v
forEach ( ) method added in Iterable interface
forEach ( ) method is a default method (it is having body)
This is method is used to access each element of the collection
(traverse collection from start to end)
Example :
package in.sbit.java8;
import java.util.ArrayList;
public class NumbersSort1 {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(3);
al.add(4);
al.add(1);
al.add(2);
al.forEach(i -> System.out.println(i));
}}
StringJoiner
java.util.StringJoiner class introduced in java 1.8v
It is used to join more than one String with specified delimiter
We can concat prefix and suffix while joininging strings using
StringJoiner
StringJoiner sj = new StringJoiner (CharSequence delim);
StringJoiner sj = new StringJoiner (CharSequence delim, CharSequence
prefix, CharSequence suffix);
Example :
package in.sb.java8;
importjava.util.StringJoiner;
public class StringJoinerDemo {
public static void main(String[] args) {
StringJoiner sj1 = new StringJoiner("-");
sj1.add("as");
sj1.add("it");
sj1.add("java");
System.out.println(sj1); // as-it-java
StringJoiner sj2 = new StringJoiner("-", "(", ")");
sj2.add("as");
sj2.add("it");
sj2.add("java");
System.out.println(sj2); // (as-it-java)
}}