Lambda expressions, default methods in interfaces, and the new date/time API are among the major new features in Java 8. Lambda expressions allow for functional-style programming by treating functionality as a method argument or anonymous implementation. Default methods add new capabilities to interfaces while maintaining backwards compatibility. The date/time API improves on the old Calendar and Date APIs by providing immutable and easier to use classes like LocalDate.
This document introduces lambda expressions in Java 8. It provides background on why lambda expressions were added to Java, including to allow for more functional programming and parallel processing. It covers the syntax of lambda expressions, when they should and should not be used, functional interfaces, method and constructor references, referencing external variables, debugging lambda expressions, and new lambda methods added in Java 8. The document also advertises exercises for the reader to complete to practice using lambda expressions.
Java is Object Oriented Programming. Java 8 is the latest version of the Java which is used by many companies for the development in many areas. Mobile, Web, Standalone applications.
The document provides an overview of new features in Java 8 including lambda expressions, functional interfaces, default and static interface methods, method references, stream API, and date/time API. Lambda expressions allow for anonymous functions and functional interfaces provide functional signatures. Default and static interface methods allow interfaces to define implementations. Method references provide shorthand syntax for lambda expressions. The stream API supports functional-style processing of collections through intermediate and terminal operations. The new date/time API replaces the Calendar class with more easily used and immutable classes like LocalDate.
Lambda expressions allow implementing functional interfaces using anonymous functions. Method references provide a shorthand syntax for referring to existing methods as lambda expressions. The Stream API allows functional-style operations on streams of values, including intermediate and terminal operations. The new Date/Time API provides a safer and more comprehensive replacement for the previous date/time classes in Java.
Default methods and static methods allow interfaces to define new methods without breaking existing implementations. The lambda expressions feature introduces functional programming to Java through functional interfaces like Consumer and Function. The streams API provides a functional-style way to process and analyze collections through parallelization, optional return values, and collectors.
The document discusses new features in Java 8 including lambda expressions, default methods, streams, and static methods in interfaces. Lambda expressions allow for anonymous functions and method references provide shorthand syntax. Default methods enable adding new functionality to interfaces while maintaining binary compatibility. Streams support sequential and parallel aggregate operations on a sequence of elements. Static methods can now be defined in interfaces.
The document discusses new features introduced in Java 8, including allowing static and default methods in interfaces, lambda expressions, and the Stream API. Key points include: interfaces can now contain static and default methods; lambda expressions provide a concise way to implement functional interfaces and allow passing code as a method argument; and the Stream API allows operations on sequences of data through intermediate and terminal operations.
This presentaion provides and overview of the new features of Java 8, namely default methods, functional interfaces, lambdas, method references, streams and Optional vs NullPointerException.
This presentation by Arkadii Tetelman (Lead Software Engineer, GlobalLogic) was delivered at Java.io 3.0 conference in Kharkiv on March 22, 2016.
Cover Basic concept for Functional Programming in Java. Define new functional interfaces, lambda expressions, how to translate lambda expression, JVM deal with new byte code etc. This is not the perfect slides for functional programming, but trying cover simple basic functional programming.
The document discusses lambda expressions in Java 8. It provides background on the lambda calculus and functional programming. Lambda expressions allow anonymous functions and are implemented using functional interfaces in Java 8. This enables a more functional style of programming. Lambda expressions can access variables from their enclosing scope and method references provide a concise way to pass existing methods. The streams API allows functional-style operations on collections and supports sequential and parallel processing.
The document discusses Java 8 Streams, which provide a way to process data in a functional style. Streams allow operations like filter, map, and reduce to be performed lazily on collections, arrays, or I/O sources. The key aspects of streams are that they are lazy, support both sequential and parallel processing, and represent a sequence of values rather than storing them. The document provides examples of using intermediate operations like filter and map and terminal operations like forEach and collect. It also discusses spliterators, which drive streams and allow parallelization, and functional interfaces which are used with lambda expressions in streams.
This document summarizes key parts of Java 8 including lambda expressions, method references, default methods, streams API improvements, removal of PermGen space, and the new date/time API. It provides code examples and explanations of lambda syntax and functional interfaces. It also discusses advantages of the streams API like lazy evaluation and parallelization. Finally, it briefly outlines the motivation for removing PermGen and standardizing the date/time API in Java 8.
This document discusses Java 8 features including defining methods in interfaces, functional programming concepts, lambda expressions, and the stream API. Key points include: interfaces can now define default and static methods; functional programming uses declarative code, avoids mutability, and handles concurrency; lambda expressions define anonymous methods; and the stream API processes data in parallel streams to leverage multi-core architectures.
Slides aim to provide constructed information about functional programming in Java 8. To able to do that, Lambdas, Built-in Functional Interfaces and Optionals summarised with code examples.
Lambda expressions allow implementing anonymous functions more concisely. Interfaces can now contain default and static methods. Streams facilitate functional-style operations on collections of elements. Optional handles null references more gracefully. The Date/Time API replaces the previous Date and Calendar classes. Nashorn allows executing JavaScript code from Java. Various new tools like jdeps were introduced.
The document discusses Java architecture and fundamentals. It can be summarized as:
1. Java's architecture consists of four main components: the Java programming language, Java class files, the Java API, and the Java Virtual Machine (JVM).
2. When a Java program is written and run, it uses these four technologies. The program is written in Java source code and compiled to class files, which are then run on the JVM along with the Java API library.
3. The JVM handles execution by using areas like the method area for bytecode storage, the Java stack for method calls and parameters, and the heap for object instantiation and garbage collection.
The document discusses Java architecture and fundamentals. It can be summarized as:
1. Java's architecture consists of four main components: the Java programming language, Java class files, the Java API, and the Java Virtual Machine (JVM).
2. When a Java program is written and run, it uses these four technologies. The program is written in Java source code and compiled to class files, which are then run on the JVM along with the Java API library.
3. The JVM handles execution by using areas like the method area for bytecode storage, the Java stack for method calls and parameters, and the heap for object instantiation and garbage collection.
The document discusses Java architecture and fundamentals. It can be summarized as:
1. Java's architecture consists of four main components: the Java programming language, Java class files, the Java API, and the Java Virtual Machine (JVM).
2. When a Java program is written and run, it uses these four technologies. The program is written in Java source code and compiled to class files, which are then run on the JVM along with the Java API library.
3. The JVM handles execution by using areas like the method area for bytecode storage, the Java stack for method calls and parameters, and the heap for object instantiation and garbage collection.
Java 8 introduced several new features including lambda expressions, default methods in interfaces, streams API and others. Lambda expressions allow implementing functional interfaces using anonymous functions. Interfaces can now define default and static methods. The streams API allows performing bulk operations on collections in a declarative way. Some performance improvements in Java 8 include faster common data structures like HashMap, garbage collector improvements and enhanced fork/join framework.
Lambda expressions in Java 8 enable functional programming and allow code blocks to be treated as values. They provide a more readable and concise syntax than traditional anonymous classes. Lambdas improve APIs and support parallel processing. Functional programming separates code from objects and allows independent functions. Lambda expressions infer types from functional interfaces and can implement interfaces like Runnable more concisely than anonymous classes. Java 8 defines functional interfaces to have a single abstract method to be compatible with lambdas. Common functional interfaces include Predicate and Consumer. Streams and Optional are new classes that work with lambdas to support functional-style operations on collections and optional values.
Java 8 introduced new features like default methods, lambda expressions, and stream API. Default methods allow interfaces to provide implementation without breaking existing classes. Lambda expressions enable functional programming by allowing blocks of code to be treated as values. The stream API allows functional-style processing of data such as filtering, mapping, and reducing collections. Some limitations of streams include that they are not reusable, can have worse performance than loops, and are less familiar to procedural programmers.
1) Java 8 introduced many new features to support functional programming in Java, such as lambda expressions, default methods in interfaces, and streams.
2) Lambda expressions allow implementing functional interfaces with anonymous methods, avoiding the need to create anonymous inner classes.
3) Default methods allow adding new methods to interfaces without breaking existing implementations, and streams allow performing bulk operations on collections in a declarative way.
Java 8 was released in 2014 and introduced several new features including lambda expressions, functional interfaces, method references, and default methods in interfaces. It also included a new Stream API for functional-style data processing, a date/time API, and Project Nashorn for embedding JavaScript in Java applications. Future versions like Java 9 will focus on modularity, new APIs, and further improvements.
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schoolsdogden2
Algebra 1 is often described as a “gateway” class, a pivotal moment that can shape the rest of a student’s K–12 education. Early access is key: successfully completing Algebra 1 in middle school allows students to complete advanced math and science coursework in high school, which research shows lead to higher wages and lower rates of unemployment in adulthood.
Learn how The Atlanta Public Schools is using their data to create a more equitable enrollment in middle school Algebra classes.
This presentaion provides and overview of the new features of Java 8, namely default methods, functional interfaces, lambdas, method references, streams and Optional vs NullPointerException.
This presentation by Arkadii Tetelman (Lead Software Engineer, GlobalLogic) was delivered at Java.io 3.0 conference in Kharkiv on March 22, 2016.
Cover Basic concept for Functional Programming in Java. Define new functional interfaces, lambda expressions, how to translate lambda expression, JVM deal with new byte code etc. This is not the perfect slides for functional programming, but trying cover simple basic functional programming.
The document discusses lambda expressions in Java 8. It provides background on the lambda calculus and functional programming. Lambda expressions allow anonymous functions and are implemented using functional interfaces in Java 8. This enables a more functional style of programming. Lambda expressions can access variables from their enclosing scope and method references provide a concise way to pass existing methods. The streams API allows functional-style operations on collections and supports sequential and parallel processing.
The document discusses Java 8 Streams, which provide a way to process data in a functional style. Streams allow operations like filter, map, and reduce to be performed lazily on collections, arrays, or I/O sources. The key aspects of streams are that they are lazy, support both sequential and parallel processing, and represent a sequence of values rather than storing them. The document provides examples of using intermediate operations like filter and map and terminal operations like forEach and collect. It also discusses spliterators, which drive streams and allow parallelization, and functional interfaces which are used with lambda expressions in streams.
This document summarizes key parts of Java 8 including lambda expressions, method references, default methods, streams API improvements, removal of PermGen space, and the new date/time API. It provides code examples and explanations of lambda syntax and functional interfaces. It also discusses advantages of the streams API like lazy evaluation and parallelization. Finally, it briefly outlines the motivation for removing PermGen and standardizing the date/time API in Java 8.
This document discusses Java 8 features including defining methods in interfaces, functional programming concepts, lambda expressions, and the stream API. Key points include: interfaces can now define default and static methods; functional programming uses declarative code, avoids mutability, and handles concurrency; lambda expressions define anonymous methods; and the stream API processes data in parallel streams to leverage multi-core architectures.
Slides aim to provide constructed information about functional programming in Java 8. To able to do that, Lambdas, Built-in Functional Interfaces and Optionals summarised with code examples.
Lambda expressions allow implementing anonymous functions more concisely. Interfaces can now contain default and static methods. Streams facilitate functional-style operations on collections of elements. Optional handles null references more gracefully. The Date/Time API replaces the previous Date and Calendar classes. Nashorn allows executing JavaScript code from Java. Various new tools like jdeps were introduced.
The document discusses Java architecture and fundamentals. It can be summarized as:
1. Java's architecture consists of four main components: the Java programming language, Java class files, the Java API, and the Java Virtual Machine (JVM).
2. When a Java program is written and run, it uses these four technologies. The program is written in Java source code and compiled to class files, which are then run on the JVM along with the Java API library.
3. The JVM handles execution by using areas like the method area for bytecode storage, the Java stack for method calls and parameters, and the heap for object instantiation and garbage collection.
The document discusses Java architecture and fundamentals. It can be summarized as:
1. Java's architecture consists of four main components: the Java programming language, Java class files, the Java API, and the Java Virtual Machine (JVM).
2. When a Java program is written and run, it uses these four technologies. The program is written in Java source code and compiled to class files, which are then run on the JVM along with the Java API library.
3. The JVM handles execution by using areas like the method area for bytecode storage, the Java stack for method calls and parameters, and the heap for object instantiation and garbage collection.
The document discusses Java architecture and fundamentals. It can be summarized as:
1. Java's architecture consists of four main components: the Java programming language, Java class files, the Java API, and the Java Virtual Machine (JVM).
2. When a Java program is written and run, it uses these four technologies. The program is written in Java source code and compiled to class files, which are then run on the JVM along with the Java API library.
3. The JVM handles execution by using areas like the method area for bytecode storage, the Java stack for method calls and parameters, and the heap for object instantiation and garbage collection.
Java 8 introduced several new features including lambda expressions, default methods in interfaces, streams API and others. Lambda expressions allow implementing functional interfaces using anonymous functions. Interfaces can now define default and static methods. The streams API allows performing bulk operations on collections in a declarative way. Some performance improvements in Java 8 include faster common data structures like HashMap, garbage collector improvements and enhanced fork/join framework.
Lambda expressions in Java 8 enable functional programming and allow code blocks to be treated as values. They provide a more readable and concise syntax than traditional anonymous classes. Lambdas improve APIs and support parallel processing. Functional programming separates code from objects and allows independent functions. Lambda expressions infer types from functional interfaces and can implement interfaces like Runnable more concisely than anonymous classes. Java 8 defines functional interfaces to have a single abstract method to be compatible with lambdas. Common functional interfaces include Predicate and Consumer. Streams and Optional are new classes that work with lambdas to support functional-style operations on collections and optional values.
Java 8 introduced new features like default methods, lambda expressions, and stream API. Default methods allow interfaces to provide implementation without breaking existing classes. Lambda expressions enable functional programming by allowing blocks of code to be treated as values. The stream API allows functional-style processing of data such as filtering, mapping, and reducing collections. Some limitations of streams include that they are not reusable, can have worse performance than loops, and are less familiar to procedural programmers.
1) Java 8 introduced many new features to support functional programming in Java, such as lambda expressions, default methods in interfaces, and streams.
2) Lambda expressions allow implementing functional interfaces with anonymous methods, avoiding the need to create anonymous inner classes.
3) Default methods allow adding new methods to interfaces without breaking existing implementations, and streams allow performing bulk operations on collections in a declarative way.
Java 8 was released in 2014 and introduced several new features including lambda expressions, functional interfaces, method references, and default methods in interfaces. It also included a new Stream API for functional-style data processing, a date/time API, and Project Nashorn for embedding JavaScript in Java applications. Future versions like Java 9 will focus on modularity, new APIs, and further improvements.
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schoolsdogden2
Algebra 1 is often described as a “gateway” class, a pivotal moment that can shape the rest of a student’s K–12 education. Early access is key: successfully completing Algebra 1 in middle school allows students to complete advanced math and science coursework in high school, which research shows lead to higher wages and lower rates of unemployment in adulthood.
Learn how The Atlanta Public Schools is using their data to create a more equitable enrollment in middle school Algebra classes.
Understanding P–N Junction Semiconductors: A Beginner’s GuideGS Virdi
Dive into the fundamentals of P–N junctions, the heart of every diode and semiconductor device. In this concise presentation, Dr. G.S. Virdi (Former Chief Scientist, CSIR-CEERI Pilani) covers:
What Is a P–N Junction? Learn how P-type and N-type materials join to create a diode.
Depletion Region & Biasing: See how forward and reverse bias shape the voltage–current behavior.
V–I Characteristics: Understand the curve that defines diode operation.
Real-World Uses: Discover common applications in rectifiers, signal clipping, and more.
Ideal for electronics students, hobbyists, and engineers seeking a clear, practical introduction to P–N junction semiconductors.
Geography Sem II Unit 1C Correlation of Geography with other school subjectsProfDrShaikhImran
The correlation of school subjects refers to the interconnectedness and mutual reinforcement between different academic disciplines. This concept highlights how knowledge and skills in one subject can support, enhance, or overlap with learning in another. Recognizing these correlations helps in creating a more holistic and meaningful educational experience.
Exploring Substances:
Acidic, Basic, and
Neutral
Welcome to the fascinating world of acids and bases! Join siblings Ashwin and
Keerthi as they explore the colorful world of substances at their school's
National Science Day fair. Their adventure begins with a mysterious white paper
that reveals hidden messages when sprayed with a special liquid.
In this presentation, we'll discover how different substances can be classified as
acidic, basic, or neutral. We'll explore natural indicators like litmus, red rose
extract, and turmeric that help us identify these substances through color
changes. We'll also learn about neutralization reactions and their applications in
our daily lives.
by sandeep swamy
The ever evoilving world of science /7th class science curiosity /samyans aca...Sandeep Swamy
The Ever-Evolving World of
Science
Welcome to Grade 7 Science4not just a textbook with facts, but an invitation to
question, experiment, and explore the beautiful world we live in. From tiny cells
inside a leaf to the movement of celestial bodies, from household materials to
underground water flows, this journey will challenge your thinking and expand
your knowledge.
Notice something special about this book? The page numbers follow the playful
flight of a butterfly and a soaring paper plane! Just as these objects take flight,
learning soars when curiosity leads the way. Simple observations, like paper
planes, have inspired scientific explorations throughout history.
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsDrNidhiAgarwal
Unemployment is a major social problem, by which not only rural population have suffered but also urban population are suffered while they are literate having good qualification.The evil consequences like poverty, frustration, revolution
result in crimes and social disorganization. Therefore, it is
necessary that all efforts be made to have maximum.
employment facilities. The Government of India has already
announced that the question of payment of unemployment
allowance cannot be considered in India
Multi-currency in odoo accounting and Update exchange rates automatically in ...Celine George
Most business transactions use the currencies of several countries for financial operations. For global transactions, multi-currency management is essential for enabling international trade.
A measles outbreak originating in West Texas has been linked to confirmed cases in New Mexico, with additional cases reported in Oklahoma and Kansas. The current case count is 817 from Texas, New Mexico, Oklahoma, and Kansas. 97 individuals have required hospitalization, and 3 deaths, 2 children in Texas and one adult in New Mexico. These fatalities mark the first measles-related deaths in the United States since 2015 and the first pediatric measles death since 2003.
The YSPH Virtual Medical Operations Center Briefs (VMOC) were created as a service-learning project by faculty and graduate students at the Yale School of Public Health in response to the 2010 Haiti Earthquake. Each year, the VMOC Briefs are produced by students enrolled in Environmental Health Science Course 581 - Public Health Emergencies: Disaster Planning and Response. These briefs compile diverse information sources – including status reports, maps, news articles, and web content– into a single, easily digestible document that can be widely shared and used interactively. Key features of this report include:
- Comprehensive Overview: Provides situation updates, maps, relevant news, and web resources.
- Accessibility: Designed for easy reading, wide distribution, and interactive use.
- Collaboration: The “unlocked" format enables other responders to share, copy, and adapt seamlessly. The students learn by doing, quickly discovering how and where to find critical information and presenting it in an easily understood manner.
CURRENT CASE COUNT: 817 (As of 05/3/2025)
• Texas: 688 (+20)(62% of these cases are in Gaines County).
• New Mexico: 67 (+1 )(92.4% of the cases are from Eddy County)
• Oklahoma: 16 (+1)
• Kansas: 46 (32% of the cases are from Gray County)
HOSPITALIZATIONS: 97 (+2)
• Texas: 89 (+2) - This is 13.02% of all TX cases.
• New Mexico: 7 - This is 10.6% of all NM cases.
• Kansas: 1 - This is 2.7% of all KS cases.
DEATHS: 3
• Texas: 2 – This is 0.31% of all cases
• New Mexico: 1 – This is 1.54% of all cases
US NATIONAL CASE COUNT: 967 (Confirmed and suspected):
INTERNATIONAL SPREAD (As of 4/2/2025)
• Mexico – 865 (+58)
‒Chihuahua, Mexico: 844 (+58) cases, 3 hospitalizations, 1 fatality
• Canada: 1531 (+270) (This reflects Ontario's Outbreak, which began 11/24)
‒Ontario, Canada – 1243 (+223) cases, 84 hospitalizations.
• Europe: 6,814
How to manage Multiple Warehouses for multiple floors in odoo point of saleCeline George
The need for multiple warehouses and effective inventory management is crucial for companies aiming to optimize their operations, enhance customer satisfaction, and maintain a competitive edge.
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...larencebapu132
This is short and accurate description of World war-1 (1914-18)
It can give you the perfect factual conceptual clarity on the great war
Regards Simanchala Sarab
Student of BABed(ITEP, Secondary stage)in History at Guru Nanak Dev University Amritsar Punjab 🙏🙏
Odoo Inventory Rules and Routes v17 - Odoo SlidesCeline George
Odoo's inventory management system is highly flexible and powerful, allowing businesses to efficiently manage their stock operations through the use of Rules and Routes.
*Metamorphosis* is a biological process where an animal undergoes a dramatic transformation from a juvenile or larval stage to a adult stage, often involving significant changes in form and structure. This process is commonly seen in insects, amphibians, and some other animals.
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingCeline George
The Accounting module in Odoo 17 is a complete tool designed to manage all financial aspects of a business. Odoo offers a comprehensive set of tools for generating financial and tax reports, which are crucial for managing a company's finances and ensuring compliance with tax regulations.
Presentation of the MIPLM subject matter expert Erdem KayaMIPLM
Ad
Unit-3.pptx.pdf java api knowledge apiii
1. Unit-3
Java New Features: Functional Interfaces, Lambda Expression, Method
References, Stream API, Default Methods, Static Method, Base64 Encode and
Decode, ForEach Method, Try-with resources, Type Annotations, Repeating
Annotations, Java Module System, Diamond Syntax with Inner Anonymous
Class, Local Variable Type Inference, Switch Expressions, Yield Keyword, Text
Blocks, Records, Sealed Classes
2. Functional Interfaces in Java
•Java has forever remained an Object-Oriented Programming language.
•By object-oriented programming language, we can declare that
everything present in the Java programming language rotates
throughout the Objects, except for some of the primitive data types
and primitive methods for integrity and simplicity.
•There are no solely functions present in a programming language
called Java.
•Functions in the Java programming language are part of a class, and if
someone wants to use them, they have to use the class or object of the
class to call any function.
3. Java Functional Interfaces
• A functional interface is an interface that contains only one abstract method.
• They can have only one functionality to exhibit.
• From Java 8 onwards, lambda expressions can be used to represent the instance of
a functional interface.
• A functional interface can have any number of default methods.
• Example - Runnable, ActionListener, and Comparable
• Functional Interface is additionally recognized as Single Abstract Method
Interfaces.
• In short, they are also known as SAM interfaces. Functional interfaces in Java are
the new feature that provides users with the approach of fundamental
programming.
4. • Functional interfaces are included in Java SE 8 with Lambda expressions and Method
references in order to make code more readable, clean, and straightforward.
• Functional interfaces are interfaces that ensure that they include precisely only one
abstract method.
• Functional interfaces are used and executed by representing the interface with
an annotation called @FunctionalInterface.
• As described earlier, functional interfaces can contain only one abstract method.
However, they can include any quantity of default and static methods.
• In Functional interfaces, there is no need to use the abstract keyword as it is optional to
use the abstract keyword because, by default, the method defined inside the interface is
abstract only.
• We can also call Lambda expressions as the instance of functional interface.
5. Lambda Expressions
•Lambda Expressions were added in Java 8.
•A lambda expression is a short block of code which
takes in parameters and returns a value.
•Lambda expressions are similar to methods, but they
do not need a name and they can be implemented right
in the body of a method.
6. Lambda Expression in Java
•In Java, Lambda expressions basically express instances of
functional interfaces (An interface with a single abstract method
is called a functional interface). Lambda Expressions in Java
are the same as lambda functions which are the short block of
code that accepts input as parameters and returns a resultant
value. Lambda Expressions are recently included in Java SE 8.
9. Java Lambda Expression Syntax
(argument-list) → {body}
Java lambda expression is consisted of three components.
1 Argument-list: It can be empty or non-empty as well.
2 Arrow-token: It is used to link arguments-list and body of expression.
3 Body: It contains expressions and statements for lambda expression.
No Parameter Syntax
() → {
//Body of no parameter lambda
}
One Parameter Syntax
(p1) → {
//Body of single parameter lambda
}
Two Parameter Syntax
(p1,p2) → { //Body of multiple parameter lambda }
13. // Java program to demonstrate lambda expressions to
// implement a user defined functional interface(one parameter).
@FunctionalInterface
interface Square {
int calculate(int x);
}
class Test {
public static void main(String args[])
{
int a = 5;
// lambda expression to define the calculate method
Square s = (int x) -> x * x;
// parameter passed and return type must be
// same as defined in the prototype
int ans = s.calculate(a);
System.out.println(ans);
}
}
14. Java Lambda Expression Example: Multiple
Parameters
interface Addable{
int add(int a,int b);
}
public class LambdaExpressionExample5
public static void main(String[] args) {
// Multiple parameters in lambda expression
Addable ad1a,ba+b;
System.out.println(ad1.add(10,20));
// Multiple parameters with data type in lambda expression
Addable ad2int a,int b)→(a+b);
System.out.println(ad2.add(100,200));
}
}
Test it No
Output:
30 300
15. Java Lambda Expression Example: with or
without return keyword
interface Addable{
int add(int a,int b);
}
public class LambdaExpressionExample6 {
public static void main(String[] args) {
// Lambda expression without return keyword.
Addable ad1a,ba+b;
System.out.println(ad1.add(10,20));
// Lambda expression with return keyword.
Addable ad2int a,int b)→{
return (a+b);
};
System.out.println(ad2.add(100,200));
}
}
Test it No
Output:
30 300
16. // Define a functional interface with a single abstract
method
@FunctionalInterface
interface ArithmeticOperation {
int operate(int a, int b);
}
public class Main {
public static void main(String[] args) {
// Implement the interface using a lambda
expression for addition
ArithmeticOperation add = (a, b) -> a + b;
// Implement the interface using a lambda
expression for subtraction
ArithmeticOperation subtract = (a, b) -> a - b;
// Implement the interface using a lambda
expression for multiplication
ArithmeticOperation multiply = (a, b) -> a * b;
// Implement the interface using a lambda expression
for division
ArithmeticOperation divide = (a, b) -> {
if (b == 0) {
throw new ArithmeticException("Division by
zero");
}
return a / b;
};
// Using the implemented lambda expressions
System.out.println("Addition: " +
add.operate(5,3));
System.out.println("Subtraction: " +
subtract.operate(5, 3));
System.out.println("Multiplication: " +
multiply.operate(5, 3));
System.out.println("Division: " + divide.operate(5,
3));
}
}
17. • ArithmeticOperation is a functional interface with a single abstract method
operate, which takes two integer arguments and returns an integer. This
method can be implemented to perform any binary operation on two
integers.
• Lambda expressions provide a clear and concise way to implement
functional interfaces without the need for anonymous classes. A lambda
expression consists of a set of parameters, an arrow (->), and a body.
• Addition:
ArithmeticOperation add = (a, b) -> a + b;
Here, add is an instance of ArithmeticOperation where the operate
method is implemented to return the sum of a and b.
• Subtraction:
ArithmeticOperation subtract = (a, b) -> a - b;
Similar to addition, this lambda expression subtracts b from a.
18. • Multiplication:
ArithmeticOperation multiply = (a, b) -> a * b;
This multiplies the two arguments.
• Division:
ArithmeticOperation divide = (a, b) -> {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
};
• This is a more complex lambda expression that first checks if the divisor b is zero,
throwing an ArithmeticException if true, otherwise it returns the division of a by b.
19. 4. Using Lambda Expressions
•In the main method, these lambda expressions are used like any other
object:
• System.out.println("Addition: " + add.operate(5, 3));
• System.out.println("Subtraction: " + subtract.operate(5, 3));
• System.out.println("Multiplication: " + multiply.operate(5, 3));
• System.out.println("Division: " + divide.operate(5, 3));
•Each operate method of different instances (add, subtract, multiply,
divide) is called with specific arguments (5 and 3). The lambda
expressions defined for each instance determine the operation
performed.
20. Method References in java
•Method references are a feature of Java 8 that allows you to
refer to a method without having to call it. This can be useful in
a number of situations, such as when you need to pass a
method as an argument to another method.
•There are four types of method references:
• 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
21. Static method reference.
•// This method reference refers to the static method `Math.max()`
•MethodReference<Double> max = Math::max;
•// This will print the maximum of 10 and 20
•System.out.println(max.apply(10, 20));
22. Instance method reference of a
particular object:
•// This method reference refers to the instance method
`String.toUpperCase()`
•MethodReference<String> toUpperCase = String::toUpperCase;
•// This will print the string "HELLO"
•System.out.println(toUpperCase.apply("hello"));
23. Instance method reference of an
arbitrary object of a particular type:
•// This method reference refers to the instance method `List.sort()`
•MethodReference<List<String>> sort = List::sort;
•// This will sort the list in ascending order
•List<String> names = Arrays.asList("John", "Mary", "Bob");
•sort.apply(names);
•// This will print the sorted list
•System.out.println(names);
24. Constructor reference.
•// This method reference refers to the constructor for the `Person`
class
•MethodReference<Person> personConstructor = Person::new;
•// This will create a new Person object
•Person person = personConstructor.apply("John Doe");
•// This will print the person's name
•System.out.println(person.getName());
25. Method references
• Method references can be used in a number of other situations, such as
when you need to pass a method as an argument to a lambda expression.
For example, the following code shows how to use a method reference to
pass the Math.max() method to a lambda expression:
• // This lambda expression uses the `Math.max()` method to find the
maximum of two numbers
• Function<Integer, Integer> maxFunction = (a, b) -> Math.max(a, b);
• // This will print the maximum of 10 and 20
• System.out.println(maxFunction.apply(10, 20));
• Methods allow us to reuse the code without retyping the code.
26. Syntax and Usage
A method reference is described using the :: (double colon) symbol.
The general syntax is one of the following forms:
•Reference to a static method: ContainingClass::staticMethodName
•Reference to an instance method of a particular object:
instance::instanceMethodName
•Reference to an instance method of an arbitrary object of a particular
type:ContainingType::methodName
•Reference to a constructor: ClassName::new
27. Examples
1. Reference to a Static Method
• import java.util.function.Function;
• public class StaticMethodReferenceExample {
• public static void main(String[] args) {
• Function<String, Integer> stringLength = String::length;
• int length = stringLength.apply("Hello, world!");
• System.out.println("Length of the string: " + length);
• }
• }
• In this example, String::length is a static method reference that refers
to the length() method of the String class.
28. 2. Reference to an Instance Method of a Particular Object
import java.util.function.Supplier;
public class ParticularObjectInstanceMethodReferenceExample {
String name = "Java";
public static void main(String[] args) {
ParticularObjectInstanceMethodReferenceExample obj = new
ParticularObjectInstanceMethodReferenceExample();
Supplier<String> getName = obj::getName; // Method reference to a specific object's
method
String name = getName.get();
System.out.println("Name: " + name);
}
public String getName() {
return name;
}
}
Here, obj::getName refers to the getName() method of the specific obj instance.
29. 3. Reference to an Instance Method of an Arbitrary Object of a Particular Type
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ArbitraryObjectInstanceMethodReferenceExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Consumer<String> printName = System.out::println; // Method reference to an arbitrary String
object's method
names.forEach(printName);
}
}
In this case, System.out::println refers to the println() method that can be called on any String object.
30. 4. Reference to a Constructor
import java.util.function.Supplier;
import java.util.ArrayList;
public class ConstructorReferenceExample {
public static void main(String[] args) {
Supplier<ArrayList<String>> createList = ArrayList::new;
ArrayList<String> names = createList.get();
names.add("David");
names.add("Eve");
System.out.println(names);
}
}
ArrayList::new is a constructor reference that allows you to create new
ArrayList objects.
31. What is the Stream API?
• The Stream API is a framework introduced in Java 8 that enables you to express
operations on collections (lists, arrays, etc.) as a series of transformations. It's
designed to make your code more concise, readable, and potentially more
efficient by leveraging parallelism.
Key Concepts
• Stream: A sequence of elements from a source (e.g., collection, array, file) that
supports aggregate operations. It doesn't store the elements themselves.
• Pipeline: A sequence of stream operations (intermediate and terminal) that are
chained together.
• Intermediate Operations: These operations (like filter, map, sorted) transform a
stream into another stream. They're lazily evaluated, meaning they don't execute
until a terminal operation is called.
• Terminal Operations: These operations (like forEach, collect, count) produce a
final result or side effect, consuming the stream in the process.
32. Creating Streams
•From Collections: List<String> names = ...; Stream<String>
nameStream = names.stream();
•From Arrays: int[] numbers = ...; IntStream numberStream =
Arrays.stream(numbers);
•From Values: Stream<String> stream = Stream.of("Java", "Python",
"C++");
•From a Function: Stream.iterate(0, n -> n + 2).limit(10); (Creates a
stream of even numbers)
33. Stream API
•Stream operations are expressed in a declarative manner—they
describe what to do rather than how to do it.
•Key Features of Stream API
•Declarative Programming: Allows you to express operations
on data sequences succinctly and clearly.
•Pipeline Processing: Streams can be pipelined to achieve
greater efficiency. Operations can be executed lazily to avoid
processing all data until it is necessary.
•Parallelism: Streams support parallel processing, which can
lead to significant performance improvements in multi-core
environments.
34. Components of the Stream API
•The Stream API consists of a source, zero or more intermediate
operations, and a terminal operation:
• Source: Streams can be created from collections, arrays, files, and other data
sources.
• Intermediate Operations: Transform the stream into another one, such as
filter, map, and sorted.
• Terminal Operations: Produce a result or side-effect, such as forEach, collect,
or reduce.
35. Common Stream Operations
•Creating a Stream
•From a collection: Collection.stream() or Collection.parallelStream()
•From an array: Arrays.stream(T[] array)
•Of specific elements: Stream.of(T... values)
36. Intermediate Operations
•filter(Predicate<T>): Returns a stream consisting of elements that
match the given predicate.
•map(Function<T, R>): Returns a stream where each element is
replaced by the result of applying a function to it.
•sorted(): Returns a stream with elements sorted according to natural
order or a provided comparator.
37. Terminal Operations
•forEach(Consumer<T>): Performs an action for each element of the
stream.
•collect(Collectors): Transforms the elements into a different form,
often a collection like a List or a Map.
•reduce(BinaryOperator<T>): Combines elements of the stream
sequentially and returns an optional reduced value.
38. Example: Using the Stream API
import java.util.*;
import java.util.stream.*;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class Stream {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("John", 30),
new Person("Jane", 25),
new Person("Greg", 18),
new Person("Sara", 20),
new Person("Harold", 40)
);
39. • // Example 1: Filter and print names of people
older than 25
• System.out.println("People older than
25:");
• people.stream()
• .filter(p -> p.getAge() > 25)
• .forEach(p ->
System.out.println(p.getName()));
• // Example 2: Calculate average age of all
people
• double averageAge = people.stream()
• .mapToInt(Person::getAge)
• .average()
• .getAsDouble();
• System.out.println("Average age: " +
averageAge);
• // Example 3: Check if there is anyone younger
than 18
• boolean anyYoungerThan18 =
people.stream()
• .anyMatch(p ->
p.getAge() < 18);
• System.out.println("Any person younger
than 18: " + anyYoungerThan18);
• // Example 4: Collect names into a list
• List<String> names = people.stream()
• .map(Person::getName)
• .collect(Collectors.toList());
• System.out.println("Names: " + names);
40. •// Example 5: Get a list of all ages
sorted
List<Integer> ages = people.stream()
.map(Person::getAge)
.sorted()
.collect(Collectors.toList());
System.out.println("Sorted ages: " +
ages);
}
}
•People older than 25:
•John
•Harold
•Average age: 26.6
•Any person younger
than 18: false
•Names: [John, Jane,
Greg, Sara, Harold]
•Sorted ages: [18, 20,
25, 30, 40]