unit-3 JAVA
unit-3 JAVA
Single Parameter:
x -> x * x
Multiple Parameters:
(a, b) -> a + b
Method References
• Introduced In: Java 8
• Method references provide a way to refer to methods
directly by their names.
• Purpose: They simplify lambda expressions by reducing
boilerplate code.
Types of Method References
• Four Main Types:
• Reference to a static method
• Reference to an instance method of a particular object
• Reference to an instance method of an arbitrary object of a
particular type
• Reference to a constructor
Method References
• Basic Syntax:
1. Static methods: ClassName::methodName
2. Instance methods of a particular object:
instance::methodName
3. Instance methods of an arbitrary object:
ClassName::methodName
4. Constructors: ClassName::new
import java.util.Arrays;
import java.util.Arrays; import java.util.List;
import java.util.List;
class Show
{
1 2
class Show
public static void display(String s) {
{ public void display(String s)
System.out.println(s); {
} System.out.println(s);
} }
public class Demo6 { }
public static void main(String...strings) public class Demo6 {
{ public static void main(String...strings)
List<String> list = Arrays.asList("Alex", {
"Brian", "Charles"); List<String> list = Arrays.asList("Alex",
list.forEach(Show::display); "Brian", "Charles");
} Show s=new Show();
} list.forEach(s::display);
}
}
import java.util.Arrays; @FunctionalInterface
3
import java.util.List; interface MyInf {
class Show{ public Student get(String str);
String msg;
Show(String s){msg=s;}
}
class Student {
4
public void display() private String str;
{ public Student(String str) {
System.out.println(this.msg); this.str = str;
} System.out.println("The name of the student
} is: " + str);
public class Demo6 { }
public static void main(String...strings) }
{ public class Demo7 {
List<Show> list = Arrays.asList(new public static void main(String[] args) {
Show("Alex"),new Show("Brian"),new MyInf constructorRef = Student :: new; //
Show("Charles")); constructor reference
list.forEach(Show::display); constructorRef.get("Aditya");
} }
} }
Use of Package java.util.function
• This java.util.function package provides
standard library-based functional interfaces
for common requirements with their
corresponding lambda expression, which
can be used by the programmer in his code
instead of creating brand new functional
interfaces.
Function
• This interface has one function apply (), this function takes
one input parameter as T and
• return value as R after performing some kind of operation
on the input parameter.
• Structure of Function interface:
@FunctionalInterface
public interface Function <T, R> {
R apply (T t);
}
This T and R may have any type of value like Integer, Float,
Double, String, etc.
import java.util.List;//CODE 1 EXAMPLE
import java.util.function.Function;
public class Demo8 {
public static void main(String[] args) {
List<Float> ls=List.of(34.0f,42.6f,66.5f, 40.5f);
Function<Float, Float> fn=(f)->f/2;
ls.forEach((s)->System.out.println(fn.apply(s)));
}
}
//CODE 2 EXAMPLE
List<String> list=Arrays.asList("Hello ","Hi ","Welcome ");
System.out.println(list);
Function<String, String> msg=s->s+"Rinki";
list.forEach(s->System.out.println(msg.apply(s)));
BiFunction
• This interface also has one function apply (), this function
takes two input parameters as T and
• U and returns a value as R after performing some kind of
operation on given input parameters.
• Structure of BiFunction interface:
@FunctionalInterface
public interface BiFunction <T, U, R> {
R apply (T t, U u);
}
• This T, U, and R may have any type of value like Integer,
Float, Double, String, etc.
import java.util.Set;//EXAMPLE 1
import java.util.function.BiFunction;
public class Demo9 {
public static void main(String...strings)
{
BiFunction<String, String, String> bi=
(s1,s2)->s1+":"+s2.toUpperCase();
Set<String> set=Set.of("Lion","Tiger","Jagaur");
set.forEach((s)->System.out.println(bi.apply(s,
s)));
}
}
List<String> al=Arrays.asList("Bob","Alex","Cloe","Ethen","Astor");
al.stream().map((s)->s+" thomason").forEach(System.out::println);
A map operation applies a function to each element of the input stream to produce another output
stream. The number of elements in the input and output streams is the same. The operation does
not modify the number of elements of the input stream.
import java.util.Comparator;
import java.util.List; Output:49
public class Demo11 {
public static void main(String[] args) {
List<Person> people = List.of(new Person(26,"Shiva"),new Person(32,"Amit"),new
Person(32,"Amit"),
new Person(23,"Sanjay"),new Person(24,"Vinod"),new Person(32,"Narendra"));
int age=people.stream().filter(p->(p.name).startsWith("S")).map(p-
>p.age).reduce(0,Integer::sum);
System.out.println(age);
}}
Method referencing
import java.util.*;
import java.util.stream.Collectors; Program to group the Persons according to
public class Demo11 { age
public static void main(String[] args) {
List<Person> people = List.of(new Person(26,"Shiva"),new Person(32,"Amit"),new
Person(32,"Amit"),new Person(23,"Sanjay"),new Person(24,"Vinod"),new
Person(32,"Narendra"));
Map<Integer, List<Person>> peopleByAge = people.stream()
.filter(p -> p.age > 20)//INTERMEDIATE
.sorted(Comparator.comparing(p->p.age)) //INTERMEDIATE
.collect(Collectors.groupingBy(p->p.age));//TERMINAL
peopleByAge.forEach((k,v)->System.out.println(k+" "+v));
}}
Base64 Encode and Decode
• Java SE provides built-in support for Base64 encoding
and decoding
• java.util.Base64 class in Java 8 and later versions.
Real-world applications of Base64 encoding in Java:
• Integrating with web services.
• Storing binary data in databases.
• Handling attachments in email clients.
Base64.Decoder This class implements a decoder for decoding byte data using the Base64
encoding scheme as specified in RFC 4648 and RFC 2045.
Base64.Encoder This class implements an encoder for encoding byte data using the Base64
encoding scheme as specified in RFC 4648 and RFC 2045.
import java.util.Base64;
public class Base64Ex {
public static void main(String[] args) {
// Java 8 and later
//Encoding
String originalInput = "Hello";
String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());
System.out.println("Encoded string: " + encodedString);
//Decoding
String encodedStringnow = "SGVsbG8=";
byte[] decodedBytes = Base64.getDecoder().decode(encodedStringnow);
String decodedString = new String(decodedBytes);
System.out.println("Decoded string: " + decodedString);
}
}
forEach Method in Java
• in Java 8 forEach was introduced as a method for
iterating over collections.
• It simplifies iteration and enhances code readability.
• Iterates over each element in the collection.
• Executes the specified action (lambda expression or
method reference) for each element.
•Advantages: •Limitations
•Cleaner and more expressive code. •Performance implications
•Encourages functional programming
with heavy computations.
style.
•Suitable for use with lambdas and
•Limited control over
method references. iteration (e.g., cannot break
out of the loop).
public class ForEachDemo {
public static void main(String[] args) {
Consumer<Integer> consumer=(x)->System.out.print(x+" ");
List<Integer> list=List.of(3,5,1,6,7,8,7);
list.forEach(consumer);//with java.util.Consumer
List.forEach((x)->System.out.print(x+" "));
list.forEach(System.out::print);//method referencing
}
}
Try-with-resources
• Simplifies resource management by automatically closing
resources.
• Resources declared in the try block are automatically closed
at the end of the block.(For example, a File resource or a
Socket connection resource.)
• No explicit finally block needed for resource cleanup.
• any object as a resource that implements java.lang.AutoCloseable, which
includes all objects which implement java.io.Closeable can be passed to try
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Demo {
public static void main(String[] args) {
try(FileWriter fw=new FileWriter("temp.txt"); BufferedWriter bw=new
BufferedWriter(fw))
{
bw.write("try with resource demo");
System.out.println("written successfully");
}
catch(IOException io)
{
io.printStackTrace();
}
}
}