UNIT 3 Part B
UNIT 3 Part B
The Lambda expression is used to provide the implementation of an interface which has
functional interface. It saves a lot of code. In case of lambda expression, we don't need to
define the method again for providing the implementation. Here, we just write the
implementation code.
Java lambda expression is treated as a function, so compiler does not create .class file.
Functional Interface
No Parameter Syntax
1. () -> {
2. //Body of no parameter lambda
3. }
1. (p1,p2) -> {
2. //Body of multiple parameter lambda
3. }
Let's see a scenario where we are not implementing Java lambda expression. Here, we are
implementing an interface without using lambda expression.
1. interface Drawable{
2. public void draw();
3. }
4. public class LambdaExpressionExample {
5. public static void main(String[] args) {
6. int width=10;
7.
8. //without lambda, Drawable implementation using anonymous class
9. Drawable d=new Drawable(){
10. public void draw(){System.out.println("Drawing "+width);}
11. };
12. d.draw();
13. }
14. }
Output:
Drawing 10
Now, we are going to implement the above example with the help of Java lambda expression.
Output:
Drawing 10
A lambda expression can have zero or any number of arguments. Let's see the examples:
1. interface Sayable{
2. public String say();
3. }
4. public class LambdaExpressionExample3{
5. public static void main(String[] args) {
6. Sayable s=()->{
7. return "I have nothing to say.";
8. };
9. System.out.println(s.say());
10. }
11. }
Output:
1. interface Sayable{
2. public String say(String name);
3. }
4.
5. public class LambdaExpressionExample4{
6. public static void main(String[] args) {
7.
8. // Lambda expression with single parameter.
9. Sayable s1=(name)->{
10. return "Hello, "+name;
11. };
12. System.out.println(s1.say("Sonoo"));
13.
14. // You can omit function parentheses
15. Sayable s2= name ->{
16. return "Hello, "+name;
17. };
18. System.out.println(s2.say("Sonoo"));
19. }
20. }
Output:
Hello, Sonoo
Hello, Sonoo
1. interface Addable{
2. int add(int a,int b);
3. }
4.
5. public class LambdaExpressionExample5{
6. public static void main(String[] args) {
7.
8. // Multiple parameters in lambda expression
9. Addable ad1=(a,b)->(a+b);
10. System.out.println(ad1.add(10,20));
11.
12. // Multiple parameters with data type in lambda expression
13. Addable ad2=(int a,int b)->(a+b);
14. System.out.println(ad2.add(100,200));
15. }
16. }
Output:
30
300
Syntax
1. ContainingClass::staticMethodName
Example 1
1. interface Sayable{
2. void say();
3. }
4. public class MethodReference {
5. public static void saySomething(){
6. System.out.println("Hello, this is static method.");
7. }
8. public static void main(String[] args) {
9. // Referring static method
10. Sayable sayable = MethodReference::saySomething;
11. // Calling interface method
12. sayable.say();
13. }
14. }
Test it Now
Output:
Example 2
Output:
Thread is running...
Syntax
1. containingObject::instanceMethodName
Example 1
In the following example, we are referring non-static methods. You can
refer methods by class object and anonymous object.
1. interface Sayable{
2. void say();
3. }
4. public class InstanceMethodReference {
5. public void saySomething(){
6. System.out.println("Hello, this is non-static method.");
7. }
8. public static void main(String[] args) {
9. InstanceMethodReference methodReference = new InstanceMethod
Reference(); // Creating object
10. // Referring non-static method using reference
11. Sayable sayable = methodReference::saySomething;
12. // Calling interface method
13. sayable.say();
14. // Referring non-static method using anonymous object
15. Sayable sayable2 = new InstanceMethodReference()::saySo
mething; // You can use anonymous object also
16. // Calling interface method
17. sayable2.say();
18. }
19. }
Output:
3) Reference to a Constructor
You can refer a constructor by using the new keyword. Here, we are
referring constructor with the help of functional interface.
Syntax
1. ClassName::new
Example
1. interface Messageable{
2. Message getMessage(String msg);
3. }
4. class Message{
5. Message(String msg){
6. System.out.print(msg);
7. }
8. }
9. public class ConstructorReference {
10. public static void main(String[] args) {
11. Messageable hello = Message::new;
12. hello.getMessage("Hello");
13. }
14. }
Output:
Hello
Java 8 Stream
Java 8 introduces Stream, which is a new abstract layer, and some new
additional packages in Java 8 called java.util.stream. A Stream is a
sequence of components that can be processed sequentially. These
packages include classes, interfaces, and enum to allow functional-style
operations on the elements.
The stream can be used by importing java.util.stream package. Stream
API is used to process collections of objects. Streams are designed to be
efficient and can support improving your program’s performance by
allowing you to avoid unnecessary loops and iterations. Streams can be
used for filtering, collecting, printing, and converting from one data
structure to another, etc.
This Java 8 Stream Tutorial will cover all the basic to advanced concepts
of Java 8 stream like Java 8 filter and collect operations, and real-life
examples of Java 8 streams.
Prerequisites for Java Stream
Before proceeding to Java 8, it’s recommended to have a basic knowledge
of Java 8 and its important concepts such as lambda expression, Optional,
method references, etc.
Note:
If we want to represent a group of objects as a single entity then we
should go for collection.
But if we want to process objects from the collection then we should go
for streams.
If we want to use the concept of streams then stream() is the method to
be used. Stream is available as an interface.
Syntax:
Stream s = c.stream();
In the above pre-tag, ‘c’ refers to the collection. So on the collection, we
are calling the stream() method and at the same time, we are storing it
as the Stream object. Henceforth, this way we are getting the Stream
object.
Note: Streams are present in java’s utility package
named java.util.stream
Let us now start with the basic components involved in streams. They as
listed as follows:
Sequence of Elements
Source
Aggregate Operations
Pipelining
Internal iteration
Features of Java Stream
A stream is not a data structure instead it takes input from
the Collections, Arrays, or I/O channels.
Streams don’t change the original data structure, they only provide the
result as per the pipelined methods.
Each intermediate operation is lazily executed and returns a stream as
a result, hence various intermediate operations can be pipelined.
Terminal operations mark the end of the stream and return the result.
Before moving ahead in the concept consider an example in which we are
having ArrayList of integers, and we suppose we apply a filter to get only
even numbers from the object inserted.
// Main class
public class GFG {
// Stream operations
// 1. Getting the stream from this collection
// 2. Filtering out only even elements
// 3. Collecting the required elements to List
List<Integer> ls
= al.stream()
.filter(i -> i % 2 == 0)
.collect(Collectors.toList());
// Print the collection after stream operation
// as stored in List object
System.out.println(
"Printing the List after stream operation : "
+ ls);
}
}
Output
// Main class
class Test {
Output
MIME
It uses the Base64 alphabet as specified in RFC 2045 for encoding and
decoding operations. The encoded output must be represented in lines of
no more than 76 characters each and uses a carriage return '\r' followed
immediately by a linefeed '\n' as the line separator. No line separator is
added to the end of the encoded output. All line separators or other
characters not found in the base64 alphabet table are ignored in decoding
operation.
Base64.Deco This class implements a decoder for decoding byte data using the Bas
der encoding scheme as specified in RFC 4648 and RFC 2045.
Base64.Enco This class implements an encoder for encoding byte data using the Bas
der encoding scheme as specified in RFC 4648 and RFC 2045.
Base64 Methods
Methods Description
Base64.Decoder Methods
Methods Description
public byte[] It decodes all bytes from the input byte array using the Bas
decode(byte[] src) encoding scheme, writing the results into a newly-allocated output b
array. The returned byte array is of the length of the resulting bytes
public int decode(byte[] It decodes all bytes from the input byte array using the Bas
src, byte[] dst) encoding scheme, writing the results into the given output byte ar
starting at offset 0.
public ByteBuffer It decodes all bytes from the input byte buffer using the Bas
decode(ByteBuffer encoding scheme, writing the results into a newly-allocated ByteBuff
buffer)
public InputStream It returns an input stream for decoding Base64 encoded byte stream
wrap(InputStream is)
Base64.Encoder Methods
Methods Description
public byte[] It encodes all bytes from the specified byte array into a newly-alloca
encode(byte[] src) byte array using the Base64 encoding scheme. The returned byte a
is of the length of the resulting bytes.
public int It encodes all bytes from the specified byte array using the Bas
encode(byte[] src, encoding scheme, writing the resulting bytes to the given output b
byte[] dst) array, starting at offset 0.
public String It encodes the specified byte array into a String using the Bas
encodeToString(byte[] encoding scheme.
src)
public ByteBuffer It encodes all remaining bytes from the specified byte buffer in
encode(ByteBuffer newly-allocated ByteBuffer using the Base64 encoding scheme. U
buffer) return, the source buffer's position will be updated to its limit; its
will not have been changed. The returned output buffer's position
be zero and its limit will be the number of resulting encoded bytes.
public OutputStream It wraps an output stream for encoding byte data using the Bas
wrap(OutputStream os) encoding scheme.
Output:
Java
import java.lang.*;
System.out.println("Default");
System.out.println("Manish Sharma");
}
sealed class Vartika extends Human
System.out.println("Vartika Dadheech");
System.out.println("Anjali Sharma");
{
Human h1 = new Anjali();
h1.printName();
h2.printName();
h3.printName();
}
Output: