0% found this document useful (0 votes)
96 views2 pages

Java 8 Lambda Expression Exercises

The document provides practice exercises for Java 8 focusing on lambda expressions and functional interfaces. It includes tasks for creating lambda expressions, utilizing built-in functional interfaces, and completing mini assignments that involve custom functional interfaces and stream operations. Additionally, it offers bonus assignments for further practice with Optional types and lambda expressions.

Uploaded by

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

Java 8 Lambda Expression Exercises

The document provides practice exercises for Java 8 focusing on lambda expressions and functional interfaces. It includes tasks for creating lambda expressions, utilizing built-in functional interfaces, and completing mini assignments that involve custom functional interfaces and stream operations. Additionally, it offers bonus assignments for further practice with Optional types and lambda expressions.

Uploaded by

venkatesh patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

Java 8 Practice Exercises – Lambda Expressions & Functional Interfaces

=====================================================================

Part 1: Lambda Expression Practice


----------------------------------

1. Write a lambda expression to add two integers and return the result.
2. Write a lambda expression to take a String and print it in uppercase.
3. Write a lambda expression to check whether a given number is even or odd.
4. Write a lambda expression to take a string and return its length.
5. Sort a list of strings using a lambda expression (ignore case while sorting).

Part 2: Built-in Functional Interface Practice


----------------------------------------------

1. Consumer<String>: Print the string in reverse.


2. Predicate<String>: Check if a string starts with "A".
3. Function<String, Integer>: Return the number of vowels in a string.
4. Supplier<String>: Return the current system time as a string.
5. BiFunction<String, String, String>: Combine two strings with a space.
6. UnaryOperator<Integer>: Square the given number.
7. BinaryOperator<Integer>: Find the maximum of two numbers.

Part 3: Mini Assignments


------------------------

Assignment 1: Custom Functional Interface


- Create your own interface:
@FunctionalInterface
interface StringModifier {
String modify(String input);
}
- Use lambdas to:
- Convert string to uppercase
- Reverse a string
- Replace all spaces with underscores

Assignment 2: Stream with Lambda


- Given a List<String> of names:
- Filter names that start with "S"
- Convert all names to uppercase
- Sort them alphabetically
- Print each name

Assignment 3: File Name Filter


- Write a program to filter files in a directory that end with ".txt" using a
lambda with FileFilter.

Assignment 4: Custom Comparator with Lambda


- Given a list of Employee objects with fields (id, name, salary), sort them:
- By name
- By salary descending

Assignment 5: Predicate Composition


- Create predicates to:
- Check if a number is positive
- Check if a number is even
- Compose both predicates to validate numbers that are positive and even
Bonus Assignment: Optional + Lambda
- Given a list of Optional<String> emails:
- Filter non-empty emails
- Convert all to lowercase
- Print each email

Happy Practicing!

Common questions

Powered by AI

Lambda expressions in Java 8 can be used to perform various operations on strings by implementing functional programming concepts. Examples include creating a lambda expression to convert a string to uppercase, reverse a string using a Consumer<String> to print it in reverse, and replacing spaces with underscores via a custom functional interface . These operations enable concise and functional manipulation of strings without boilerplate code.

Predicate composition in Java 8 facilitates complex condition validation by combining multiple predicates using logical operations. It allows checking multiple properties at once. For example, you can create a predicate to check if a number is positive and another to check if it's even, then compose them to validate numbers that are both positive and even using a lambda expression . This approach streamlines condition checks by combining predicates, providing a functional and clear validation mechanism.

Stream operations combined with lambda expressions in Java 8 allow efficient and concise data processing on collections. For instance, using streams, you can filter names starting with 'S', convert all to uppercase, sort them alphabetically, and print each name . This enables a functional programming approach, reducing complexity and enhancing readability by chaining methods in a declarative style rather than using iterative loops.

Using a custom functional interface in Java 8 benefits string manipulation tasks by allowing tailored operations specific to the task at hand. By defining an interface like StringModifier, developers can implement operations such as converting strings to uppercase, reversing them, or replacing spaces with underscores using lambdas . This increases flexibility and modularity in code, enabling custom solutions that fit specific operational needs while leveraging Java's functional programming capabilities.

The BiFunction interface in Java 8 serves as a functional method to combine two inputs and yield a result, such as concatenating two strings. For example, you can use a lambda expression with BiFunction<String, String, String> to join two strings with a space in between as: `(s1, s2) -> s1 + " " + s2` . This facilitates a modular approach to combining data, streamlining operations that require pairs of inputs.

Lambda expressions in Java 8 enhance file filtering operations by allowing concise and flexible expression of criteria. For instance, to filter files with a ".txt" extension, you can use a lambda expression with a FileFilter to succinctly express this condition . This replaces verbose anonymous classes, improving both brevity and clarity in code when handling file filtering tasks.

In Java 8, binary and unary operators enhance mathematical operations by promoting a functional programming approach through predefined functional interfaces. The UnaryOperator<T> interface allows operations like squaring a number, whereas the BinaryOperator<T> helps in finding the maximum of two numbers . These operators enable operations as reusable lambda expressions, boosting code reuse and readability while performing common tasks.

In Java 8, lambda expressions streamline sorting operations on objects by eliminating the need for verbose comparator implementations. For Employee objects, you can sort by name or salary descending using lambda expressions directly. For example, sort by name as: `Comparator.comparing(Employee::getName)`, and by salary descending using `Comparator.comparing(Employee::getSalary).reversed()` . This results in cleaner and more maintainable code.

The Optional class in Java 8, when combined with lambda expressions, significantly enhances null safety and functional style programming in collections. For instance, with a list of Optional<String> emails, you can filter non-empty emails, convert them to lowercase, and print each using methods like `filter(Optional::isPresent).map(Optional::get).map(String::toLowerCase)` . This reduces the risks of null pointer exceptions and enhances the expressiveness and safety of operations on collections.

Functional interfaces in Java 8 enable string operations by defining a single abstract method that can be implemented using lambda expressions. A Consumer<String> interface can print a string in reverse . A Predicate<String> checks if a string starts with 'A' . A Function<String, Integer> calculates the number of vowels in a string . A Supplier<String> can be used to return the current system time as a string . These interfaces facilitate various string manipulations within a streamlined functional paradigm.

You might also like