From Basic To Master Java Core Concepts With Examples + Theory
From Basic To Master Java Core Concepts With Examples + Theory
java
-the main advantage of java 8 is java has enabled functional programming like other
language
-Example 2:-
public void m1(int a,int b)
{
SOP(a+b);
}
........converting into anonymous function/Lamda Expression.....
(a,b) -> SOP(a+b);
here we also removed Datatype because compiler will by himself guess datatype
automatically
.................
-Example 3:-
public int squareIt(int n)
{
return n*n;
}
........converting into anonymous function/Lamda Expression....
(int n) -> {return n*n; }
Points to remember :-if we are writing return keyword then mandaotory we have to
use {} brackets for single line also
-we can also write above example 3 without return keyword as follow
(int n) -> n*n; // no nned to write ruturn keyword compiler will automatically
conclude it
-if the compiler can guess datatype then we also dont need to mention datatype as
follows
(n)->n*n;
-if there is only one input parameter then no need to use parentatis(() brakets)
also.Now the big line method is converted into 1 line lamda expression
n->n*n;
.................
..............
-Example 4
public void m1(String s)
{
return s.length();
}
.............converting into Lamda Expression
s->s.length();
................
...................................................................................
..............
Functional Interface :-A interface which contains only one abstract method are
called as functional Interface for
-Functional Interface can be used to call lamda Expression
-Functional Interface should contain only one abstract method but there is no
restriction for default and static method, functional Interfcae can contain
numerious default and static method there is no restriction
-@FuntionalInterface :-just to specify explicitly that an Interface is functional
interface
-this @FuntionalInterface annotation is optional the advantage of using this
annoataion is if we do any mistake compiler will give compile time error
-declaring @FuntionalInterface is optional. if our interface containing only one
abstract method then is automatically called as funtional interface
...................................................................................
................................
Functional Interface with respect to inheritance:
interface B extends A
{
}
--Example2 :-if parent is functional interface then child is also functional
interface if the child doesnt define any new abstract method
interface A
{
public void m1();
}
interface B extends A
{
public void m1();
}
--Example 3:-it is invalid because now child interface contains 2 abstract method
one is from parent and one is defined in child which is m2()
interface A
{
public void m1();
}
interface B extends A
{
public void m2();
}
.................................................................................
Lamda Expression with Functional Interface:
-if we want to call lamda expression functional expression must be required
-to provide reference to lamba expression function inerface is required
-by using functional interface refernce we can call m1() method which internally
calls the pointed lamba expression
.........
Example1:-without lambda expression
interface Interf
{
public void m1();
}
interface Interf
{
public void m1();
}
class Test
{
p s v main()
{
Interf i =()->SOP("Hello");
i.m1(); //whenever
}
}
............
Example 2:-wiyhout lamba expression
interface interf
{
public void add(int a,int b)
}
Note :-here (a,b) argument will directly point to method present in interface
because functional interface contains only one abstract method
............................................................................
...................................................................................
class test
{
p s v m()
{
ArrayList<Integer> i= new ArrayList<Integer>();
i.add(20);
i.add(10);
i.add(25);
i.add(5);
SOP(l);
Comparator<Integer> c=(I1,I2)->(I1<I2)?-1:(I1>I2)?1:0;
Collections.sort(l,c);
}
}
................................................................................
Q.Sorting according to Employee number using Lamda Expression
class Employee
{
String name;
int eno;
Employee(String name,int eno)
{
this.name=name;
this.eno=eno;
}
public String toString()
{
return name+":";
}
}
class Test
{
public static void main()
{
Array:List<Employee> l= new ArrayList<Employee>();
l.add(new Employee("Durga",02));
l.add(new Employee("Sunny",05));
l.add(new Employee("Bunny",01));
l.add(new Employee(""chinny",10));
SOP(l);
collections.sort(l,(e1,e2)->(e1.eno<e2.no)?-1:(e1.eno>e2.eno)?1:0);
SOP(l);
}
}
......................................................
class Employee
{
String name;
int eno;
Employee(String name,int eno)
{
this.name=name;
this.eno=eno;
}
public String toString()
{
return name+":";
}
}
class Test
{
public static void main()
{
Array:List<Employee> l= new ArrayList<Employee>();
l.add(new Employee("Durga",02));
l.add(new Employee("Sunny",05));
l.add(new Employee("Bunny",01));
l.add(new Employee(""chinny",10));
SOP(l);
collections.sort(l,(e1,e2)->e1.name.compareTo(e2.name));
SOP(l);
}
}
............................................................................
Lamda Expression vs anonymous inner class
Note***:-observe line 5 while overriding default method we are writing 'public void
m1()' instead of 'default void m1()' because default method can only be written in
interface not in classes, as in classes meaning of default is different
-Scenario where two interface having default method with same name and how
implementating class will call required default method without getting into
ambiguity stat
interface Left
{
default void m1()
{
SOP("Left interface m1 method");
}
}
interface Right
{
default void m1()
{
SOP("Right interface m1 method");
}
}
class test implements Left,Right
{
public void m1()
{
//SOP("our own m1 method");
Left.super.m1(); // this will call m1() default method of Left interface
}
p s v main()
{
Test t = new Test();
t.m1()
}
}
...................................................................................
.......................
static methods :-From 1.8v onwards interface provided support for static methods
but this static method by default not available to implementation class
-interface static method should be called using interface name only because
implementation class wont get interface static method automatically
-Example :-interface Interf
{
public static void m1()
{
SOP("Interface static method");
}
}
class Test implements Interf
{
p s v main()
{
Interf.m1(); //valid
m1(); //invalid interface static method should be called using interface name only
Test.m1(); //invalid interface static method should be called using interface name
only
Test t = new Test(); //invalid interface static method should be called using
interface name only
t.m1();
}
}
-from i.8v onwards we can decclare static method inside interface and happily we
can invoke interface directly from cmd because interface can contain main methods
also
-to define general utility methods inside interface static method concept can be
used
-static method which are declared inside interface by default noot avaiable to the
implementation classes compulsory we have to call by using interface name only
-interface static method can be called only by using interface name
...................................................................................
...............
Q.just an example
Predicate<Employee> p=e->e.salary>3000;
for(Employee e1 : l)
{
if(p.test(e1))
{
SOP(e1.name+':'+e1.salary);
}
}
}
}
.......
Q.when to use predicate?
->if you want conditional checking in our programming with using lamda expression
then predicate finctional interface is best choice
........
...................................................................................
...................................
2)Function Functional Interface :-Programmer can use this interface when expecting
return type is not only boolean.
-it takes two argument 1.input type and 2.return type
-Example 1:-wap to get length if given input string
-it also consist only one astract method i.e apply()
class Test
{
public static void main)
{
function<String,Integer> f=s->s.lenght();
SOP(f.apply("durga"));
}
}
-Example 2:-
class Student
{
String name;
int marks;
Student(String name,int marks)
{
this.name=name;
this.marks-marks;
}
}
class Test
{
p s v main()
{
Function<Student,String> f=s->{
int marks=s.marks;
String grade="";
if(marks>=80) grade="A";
else if(marks>=60) grade="B";
ELSE if(marks>=50) grade="C";
else if(marks>=30) grade="D";
else grade=-"E"
return grade;
};
Student[] s ={ new Student ("durga"),80),new Student ("vishal"),70),
new Student ("samadan"),43),
new Student ("harshal"),15)
};
for(Student s1 : s)
{
SOP("student Name:"+s1.name);
SOP("student marks:"+s1.marks);
SOP("student grade:"+f.apply(s1));
}
}
}
...................................................................................
................
}
for(Student s1 : s)
{
c.accept(s1);
}
Example 2:-
class test
{
p s v main()
{
Consumer<Movie> c1=m->SOP(m.name+"ready to release");
Consumer<Movie> c1=m->SOP(m.name+"released but flop");
Consumer<Movie> c1=m->SOP(m.name+"storing into CD");
Consumer<Movie> cc=c1.andThen(c2).andThen(c3); //consumer chaining
Mpovie m = new Movie("Spider");
cc.accept(m);
}
}
.....................................................................
.................................................
Primitives Predicate Types:
1)IntPredicates :-Its always gonna take some one* int value and returns boolean
value
-advatages of this interface is therre will be no internal autoboxing/autounboxing
2)DoublePredicates :-Its always gonna take some one* Double value and returns
boolean value
-advatages of this interface is therre will be no internal autoboxing/autounboxing
3)LongPredicates:-Its always gonna take some one Long value and returns boolean
value
-advatages of this interface is therre will be no internal autoboxing/autounboxing
1)DoubleFunction : it can take input type as double primitve but return type can be
anytime
-it contains only one method i.e apply() no method chaining methods are available
like andThen etc
2)IntFunction :: it can take input type as int primitve but return type can be
anytime
-it contains only one method i.e apply() no method chaining methods are available
like andThen etc
3)LongFunction :: it can take input type as Long primitve but return type can be
anytype
-it contains only one method i.e apply() no method chaining methods are available
like andThen etc
4)DoubleToIntFunction :-it can take input type as double primitve but return type
is int
-it contains only one method i.e applyAsInt(double value)
5)DoubleToLongFunction :-it can take input type as double primitve but return type
is long
-it contains only one method i.e applyAsInt(double value)
6)IntToDoubleFunction :-it can ake int type as double primitive but return type is
long
-it contains only one method i.s applyAsInt()
7)IntToLongFunction :-
8)LongToIntFunction :-
9)LongToDoubleFunction :-
10)ToIntFunction :-it can take input of any type but it will return int type
-contain int applyAsInt(T value)
11)ToLongFunction :
12)ToDoubleFunction
13)ToIntBiFunction :--it takes two value as input return type must be int type but
input can ne anytype
-contains int apply (T t,U u)
14)ToLongBiFunction :-
15)ToDoubleBiFunction :-
2)DoubleConsumer
3)LongConsumer :-
4)ObjDoubleConsumer :-:-it takes one arugument of any type and osecond argument as
double value
-void accept (T t,double value)
5)ObIntConsumer :-
6)ObjLongConsumer:-
Primitives Supplier Types :-
1)BooleanSupplier :-
boolean getAsBoolean()
2)IntSupplier:-
int getAsInt()
3)LongSupplier
4)DoubleSupplier() :-
...................................................................................
...............................
UnaryOprator :-if the input and output is same type then we can use UnaryOpertaor
-it is a child class of function Functional Interface abd has appply(Object) mwthod
IntUnaryOperator :-if the input and output is of int type we can use UnaryOperator
-it contains public int applyAsInt(int)
)
LongUnaryOperator :-
DoubleUnaryOperator :-
...................................................................................
.............
BinaryOperator :-if both inputs and return type is same then go for BinaryOperator
-public T apply(T,T)
-its a child interface of BiFunctonal functional interface
1)IntBinaryOperator :-if both input primitive types are same and return tpe is also
same then go for intBinaryOperator
-contains int applyAsInt(int n, int n1);
2)LongBinaryOperator :-
3)DoubleBinaryOperator :-
...................................................................................
.............................
Example 2 :
interface Interf
{
public void add(int a,int b)
}
class Test
{
public static void m1(int x,int y)
{
SOP("the sum:"+(x+y));
}
Note :-if implementation is already available we should go for method reference and
if implementation is not available then go for lamda expression.
...................................................................................
..........................................
Constructur reference :-
class Sample
{
Sample()
{
SOP("sample class constructor Execution");
}
}
Interface Interf
{
public Sample get();
}
class Test
{
p s v main()
{
Interf i=Sample::new;
Samle s1=i.get();
}
}
...................................................................................
..........................................
Stream :- If we want to process Objects from the collection then we should go for
Stream present in java.util.Stream
-Stream is an inteface present in java.util.stream pkg
-using stream we can process obj inside collection
-Creating Stream by calling steam() method on collection i.e: Stream s = c.stream()
-if we want to filter then we should go for filter() method for e.g like filter
even object or filter odd objects.
-filter() is always based on some boolean condition thats why filter() takes
Predicate as input arg
-if there is a group of object and we have to filter some object then we should go
for filter() method
-map() method means to do some operation and return some results so return type can
to anytype so in takes funtion is input arg
-for every object do some functionality or operation generate a new object then
automatically we should go for map()
-Now after filter and map collect this result to List then we have to use
.collect(Collectors.toList()) method
-count() method is used to count how many object are thier in stream. Return type
is long
-sorted() method is called on stream to sort objects according to default natural
sorting order and returns List of processed object
-sorted(Comparator) ->customized sorting
-sorted()->natural sorting order
List<Integer>
sortedList=marks.stream().sorted((i1,i2)->(i1<i2)?1:(i1>i2)?-1:0).collect(collector
s.ToList())
SOP(sortedList);
}
}
List<Integer>
sortedList=marks.stream().sorted((i1,i2)->i2.compare(i1)).collect(collectors.ToList
())
SOP(sortedList);
}
}
.............................
Note***:
(s1,s2)->s1,compareTo(s2)->natural sorting order
(s1,s2)->s2.compare(s1)->recerse of natural sorting order
(s1,s2)->s1.compare(s2)->recerse of natural sorting order
.....................
..............................
min() & max() method:-
-
-compulsory we have to pass comparator interface as argument in min &max method or
it will not work
-Example 1:-
class Test
{
p s v main()
{
ArrayList<> marks = new Array:ist<>();
marks.add(20);
marks.add(30);
marks.add(60);
marks.add(40);
marks.add(50);
int min=marks.stream().min((i1,i2)->i2.compare(i1)).get();
//int min will give min value after sorting
sop(min)
int max=marks.stream().max((i1,i2)->i2.compare(i1)).get();
//int max will give max value after sorting(sorting depends on what logic prog. is
using)
SOP(max);
}
}
......................................
forEach :-need to learn 1:51:00 durga stream
.................................................................................
toArray() : to convert stream of objects into Array
-Example 1:-
class Test
{
p s v main()
{
ArrayList<> marks = new Array:ist<>();
marks.add(20);
marks.add(30);
marks.add(60);
marks.add(40);
marks.add(50);
(5)Integer[] i=marks.stream().toArray(Integer[]::new); // this line is example of
constructor reference where Sample::new returned new object of Sample type
for(Integer i1 : i)
{
sop(i1);
}
}
Note : here line 5 is creating new object of Integer[] Array
...................................................................................
........................................
Stream.of() :- to convert Array or group of elements together into stream
Note******: stream concept is not applicable only for collection .it is apllicable
on Array alos.It is applicable for evevry group of elements present together
p s v main()
{
Stream s=Stream.of(9,99,41,85,35,888)
s.forEach(System.out::Println);
}
}