[go: up one dir, main page]

0% found this document useful (0 votes)
12 views7 pages

Java Lambda Tutorial For Beginners

Uploaded by

tricka325
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views7 pages

Java Lambda Tutorial For Beginners

Uploaded by

tricka325
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Java 8 Tutorial for Beginners

Contents

1 Introduction to Java 8 1

2 Setting Up Java 8 1

3 Key Java 8 Features 2


3.1 Lambda Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
3.2 Functional Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3.3 Stream API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.4 Optional Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.5 New Date and Time API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.6 Default and Static Methods in Interfaces . . . . . . . . . . . . . . . . . . . . . . . 5
3.7 Method References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

4 Basic Java 8 Program Example 5

5 Best Practices and Tips 6

6 Resources for Further Learning 7

7 Conclusion 7

1 Introduction to Java 8

Java 8, released in March 2014, is a landmark version of Java that introduced functional pro-
gramming concepts, improved performance, and modernized the language. It is widely used
in enterprise applications, Android development, and backend systems. Key goals of Java 8
include:
• Improved developer productivity: Through features like lambda expressions and streams.
• Better performance: With enhancements like parallel streams.
• Modern programming paradigms: Support for functional programming alongside object-
oriented programming.
This tutorial assumes basic programming knowledge (e.g., variables, loops, classes) but no prior
experience with Java 8 features.

2 Setting Up Java 8

To start coding in Java 8:

1
1. Download and Install Java 8 JDK:
• Visit the Oracle JDK 8 download page or use OpenJDK.
• Install the JDK for your operating system (Windows, macOS, or Linux).
2. Set Up Environment Variables:
• Set JAVA_HOME to the JDK installation path (e.g., C:\Program Files\Java\jdk1.8.0_281).
• Add the JDKs bin directory to your systems PATH.
3. Verify Installation:
• Run java -version and javac -version in a terminal.
• Expected output:
1 java version " 1.8.0 _281 "
2 Java ( TM ) SE Runtime Environment ( build 1.8.0 _281 - b09 )
3 javac 1.8.0 _281

4. Choose an IDE:
• Use IntelliJ IDEA, Eclipse, or NetBeans for code completion and debugging.
5. Write Your First Program:
1 public class HelloWorld {
2 public static void main ( String [] args ) {
3 System . out . println ( " Hello , Java 8! " ) ;
4 }
5 }

Compile and run using:


1 javac HelloWorld . java
2 java HelloWorld

Output: Hello, Java 8!

3 Key Java 8 Features

3.1 Lambda Expressions


Lambda expressions enable functional programming by allowing concise method definitions.
They are used with single-method interfaces.
Syntax:
1 ( parameters ) -> expression

or
1 ( parameters ) -> { statements ; }

Example: Instead of an anonymous class for Runnable:


1 // Old way ( Java 7)
2 Runnable runnable = new Runnable () {
3 @Override
4 public void run () {
5 System . out . println ( " Running in a thread ! " ) ;

2
6 }
7 };
8 // Java 8 lambda
9 Runnable runnable = () -> System . out . println ( " Running in a thread ! " ) ;

Practice: Sort a list of strings using a lambda:


1 import java . util . Arrays ;
2 import java . util . List ;
3
4 public class LambdaExample {
5 public static void main ( String [] args ) {
6 List < String > names = Arrays . asList ( " Alice " , " Bob " , " Charlie " ) ;
7 names . sort (( a , b ) -> a . compareTo ( b ) ) ;
8 System . out . println ( names ) ; // Output : [ Alice , Bob , Charlie ]
9 }
10 }

3.2 Functional Interfaces


A functional interface has exactly one abstract method. The @FunctionalInterface annota-
tion enforces this.
Example:
1 @ Functiona l I n t e r f a c e
2 interface MyFunction {
3 void perform () ;
4 }

Used with a lambda:


1 MyFunction func = () -> System . out . println ( " Performing action ! " ) ;
2 func . perform () ;

Built-in Functional Interfaces (in java.util.function):


• Predicate<T>: Tests a condition.
• Function<T, R>: Transforms input to output.
• Consumer<T>: Performs an action on input.
• Supplier<T>: Provides a value.
Example:
1 import java . util . function . Predicate ;
2
3 public class PredicateExample {
4 public static void main ( String [] args ) {
5 Predicate < Integer > isEven = n -> n % 2 == 0;
6 System . out . println ( isEven . test (4) ) ; // true
7 System . out . println ( isEven . test (5) ) ; // false
8 }
9 }

3
3.3 Stream API
The Stream API (java.util.stream) processes collections in a functional way. Streams sup-
port operations like filtering, mapping, and reducing.
Common Operations:
• filter(Predicate): Keeps elements matching a condition.
• map(Function): Transforms elements.
• collect(Collectors.toList()): Converts stream to a collection.
• forEach(Consumer): Performs an action for each element.
Example: Filter even numbers and double them:
1 import java . util . Arrays ;
2 import java . util . List ;
3 import java . util . stream . Collectors ;
4
5 public class StreamExample {
6 public static void main ( String [] args ) {
7 List < Integer > numbers = Arrays . asList (1 , 2 , 3 , 4 , 5 , 6) ;
8 List < Integer > result = numbers . stream ()
9 . filter ( n -> n % 2 == 0)
10 . map ( n -> n * 2)
11 . collect ( Collectors . toList () ) ;
12 System . out . println ( result ) ; // Output : [4 , 8 , 12]
13 }
14 }

3.4 Optional Class


The Optional class (java.util.Optional) prevents NullPointerException by representing
a value that may or may not be present.
Example:
1 import java . util . Optional ;
2

3 public class OptionalExample {


4 public static void main ( String [] args ) {
5 String name = null ;
6 Optional < String > optionalName = Optional . ofNullable ( name ) ;
7 System . out . println ( optionalName . orElse ( " Unknown " ) ) ; // Output :
Unknown
8 Optional < String > nonEmpty = Optional . of ( " Alice " ) ;
9 nonEmpty . ifPresent ( n -> System . out . println ( " Name : " + n ) ) ; //
Output : Name : Alice
10 }
11 }

3.5 New Date and Time API


The java.time package provides a modern, thread-safe API for dates and times.
Key Classes:
• LocalDate: Represents a date (e.g., 2025-09-30).

4
• LocalDateTime: Combines date and time.
• Period: For date differences.
Example:
1 import java . time . LocalDate ;
2 import java . time . Period ;
3
4 public class DateTimeExample {
5 public static void main ( String [] args ) {
6 LocalDate today = LocalDate . now () ;
7 System . out . println ( " Today : " + today ) ;
8 LocalDate birthday = LocalDate . of (2000 , 1 , 1) ;
9 Period age = Period . between ( birthday , today ) ;
10 System . out . println ( " Age : " + age . getYears () + " years " ) ;
11 }
12 }

3.6 Default and Static Methods in Interfaces


Interfaces can now have default and static methods with implementations.
Default Method Example:
1 interface MyInterface {
2 default void sayHello () {
3 System . out . println ( " Hello from interface ! " ) ;
4 }
5 }
6 class MyClass implements MyInterface {}
7 public class D e f a u l t M e t h o d E x a m p l e {
8 public static void main ( String [] args ) {
9 MyClass obj = new MyClass () ;
10 obj . sayHello () ; // Output : Hello from interface !
11 }
12 }

3.7 Method References


Method references use the :: operator as a shorthand for lambdas.
Example:
1 import java . util . Arrays ;
2 import java . util . List ;
3
4 public class M e t h o d R e f e r e n c e E x a m p l e {
5 public static void main ( String [] args ) {
6 List < String > names = Arrays . asList ( " Alice " , " Bob " , " Charlie " ) ;
7 names . forEach ( System . out :: println ) ;
8 }
9 }

4 Basic Java 8 Program Example

A complete program combining multiple Java 8 features:

5
1 import java . util . Arrays ;
2 import java . util . List ;
3 import java . util . Optional ;
4 import java . time . LocalDate ;
5 import java . util . stream . Collectors ;
6
7 public class Java8Demo {
8 public static void main ( String [] args ) {
9 List < Person > people = Arrays . asList (
10 new Person ( " Alice " , LocalDate . of (1995 , 5 , 10) , 50000) ,
11 new Person ( " Bob " , LocalDate . of (2000 , 8 , 15) , 60000) ,
12 new Person ( null , LocalDate . of (1998 , 3 , 22) , 45000)
13 );
14 List < Person > filtered = people . stream ()
15 . filter ( p -> p . getBirthDate () .
getYear () > 1997)
16 . map ( p -> new Person ( p . getName () .
orElse ( " Unknown " ) ,
17 p.
getBirthDate () ,
18 p . getSalary ()
* 1.1) )
19 . collect ( Collectors . toList () ) ;
20 filtered . forEach ( System . out :: println ) ;
21 }
22 }
23 class Person {
24 private String name ;
25 private LocalDate birthDate ;
26 private double salary ;
27 public Person ( String name , LocalDate birthDate , double salary ) {
28 this . name = name ;
29 this . birthDate = birthDate ;
30 this . salary = salary ;
31 }
32 public Optional < String > getName () {
33 return Optional . ofNullable ( name ) ;
34 }
35 public LocalDate getBirthDate () {
36 return birthDate ;
37 }
38 public double getSalary () {
39 return salary ;
40 }
41 @Override
42 public String toString () {
43 return " Person { name = " + getName () . orElse ( " Unknown " ) +
44 " , birthDate = " + birthDate +
45 " , salary = " + salary + " } " ;
46 }
47 }

5 Best Practices and Tips

1. Use Lambda Expressions Judiciously: Keep lambdas concise; extract complex logic
to methods.

6
2. Leverage Streams for Collections: Use streams for bulk operations, but avoid for
simple tasks.
3. Handle Optionals Properly: Use orElse or orElseGet to simplify logic.
4. Use Parallel Streams Cautiously: Only for large datasets; ensure thread safety.
5. Modern Date/Time API: Prefer java.time over java.util.Date.
6. Test Your Code: Write unit tests for streams and lambdas.

6 Resources for Further Learning

• Official Documentation:
– Oracle Java 8 Documentation
– Java 8 API Reference
• Tutorials:
– Baeldung Java 8 Tutorial
– Java 8 Features by Mkyong
• Books:
– Java 8 in Action by Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft
– Modern Java in Action by the same authors
• Practice:
– Solve problems on HackerRank or LeetCode.

7 Conclusion

Java 8 introduces functional programming, better APIs, and improved productivity. By mas-
tering lambda expressions, the Stream API, Optional, and the Date/Time API, you can write
cleaner, more efficient code. Practice with small examples and explore the resources above to
deepen your understanding.

You might also like