I'm always excited to take on new projects and collaborate with innovative minds.
contact@niteshsynergy.com
https://www.niteshsynergy.com/
Java 8 introduced several new features and enhancements that revolutionized the way developers write Java code. Here's a breakdown of the key features:
Java 8 introduced several new features and enhancements that revolutionized the way developers write Java code. Here's a breakdown of the key features:
(parameters) -> expression
List<String> names = Arrays.asList("Nitesh", "Kr", "Synergy");
names.forEach(name -> System.out.println(name));
package com.niteshsynergy.java8;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.*;
public class Java8Demo1 {
public static void main(String[] args) {
// Lambda for Addition
Calculator add = (a, b) -> a + b;
// Lambda for Subtraction
Calculator subtract = (a, b) -> a - b;
// Lambda for Multiplication
Calculator multiply = (a, b) -> a * b;
// Lambda for Division (Handles division by zero with a fallback value of 0)
Calculator divide = (a, b) -> b != 0 ? a / b : 0;
// Demonstrate usage of Calculator lambdas
System.out.println("Addition: " + add.calculate(10, 5)); // Output: 15
System.out.println("Subtraction: " + subtract.calculate(10, 5)); // Output: 5
System.out.println("Multiplication: " + multiply.calculate(10, 5)); // Output: 50
System.out.println("Division: " + divide.calculate(10, 5)); // Output: 2
// List of names for sorting demonstration
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
// Lambda for custom sorting by string length
names.sort((a, b) -> Integer.compare(a.length(), b.length()));
System.out.println("Sorted Names: " + names); // Output: Sorted list by name length
// Predicate to check if a number is positive
Predicate<Integer> predicate = i -> i > 0;
if (predicate.test(10)) // Test predicate with value 10
System.out.println("Positive");
else
System.out.println("Negative");
// Consumer to print a string with a welcome message
Consumer<String> consumer = s -> {
System.out.println(s + " welcome"); // Print message with "welcome"
};
consumer.accept("Nitesh"); // Output: Nitesh welcome
// Consumer to check if a number is even
Consumer<Integer> integerConsumer = number -> {
if (number % 2 == 0)
System.out.println("Even");
};
integerConsumer.accept(2); // Output: Even
// List of integers for predicate demonstration
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
// Predicate to check if a number is positive
Predicate<Integer> isPositive = n -> n > 0;
System.out.println(isPositive.test(5)); // Output: true
System.out.println(isPositive.test(-3)); // Output: false
// List of names for consumer demonstration
List<String> names1 = Arrays.asList("Alice", "Bob", "Charlie");
Consumer<String> printName = name -> System.out.println(name);
// Use forEach with Consumer to print each name
names.forEach(printName); // Output: Alice, Bob, Charlie
// Supplier to generate a random number
Supplier<Integer> randomNumber = () -> new Random().nextInt(100);
System.out.println(randomNumber.get()); // Output: Random number (e.g., 42)
System.out.println(randomNumber.get()); // Output: Another random number (e.g., 85)
// Function to convert a string to uppercase
Function<String, String> toUpperCase = str -> str.toUpperCase();
System.out.println(toUpperCase.apply("hello")); // Output: HELLO
System.out.println(toUpperCase.apply("java")); // Output: JAVA
// BiFunction to concatenate two strings
BiFunction<String, String, String> concatenate = (str1, str2) -> str1 + str2;
System.out.println(concatenate.apply("Hello, ", "World!")); // Output: Hello, World!
System.out.println(concatenate.apply("Java ", "8")); // Output: Java 8
}
}
// Functional Interface for basic calculator operations
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}
@FunctionalInterface
(Optional but recommended).Predicate<T>
: Takes one argument, returns a boolean.Consumer<T>
: Takes one argument, returns nothing.Function<T, R>
: Takes one argument, returns a result.@FunctionalInterface
interface Greeting {
void sayHello(String name);
}
Greeting greeting = name -> System.out.println("Hello, " + name);
greeting.sayHello("Nitesh");
void run()
V call() throws Exception
java.util
package)int compare(T o1, T o2)
void actionPerformed(ActionEvent e)
Runnable
and Future
, combining the ability to run a task and return a result.boolean cancel(boolean mayInterruptIfRunning)
V get()
Predicate<T>
was formally introduced in Java 8, a simple condition-checking pattern (like boolean test(T t)
) can be implemented in earlier versions manually.forEach
(Prior to Java 8)Stream.forEach()
, you could use loops or iterators for similar purposes, though Stream
itself was introduced in Java 8.Optional
(Java 8)Optional
itself isn't a functional interface, it often works with functional programming principles. It is used to represent a value that may or may not be present.Observer
(Java 1.0)void update(Observable o, Object arg)
Iterable
(Java 1.0)Iterator<T> iterator()
Java 8 introduced the most significant collection of predefined functional interfaces (Function
, Predicate
, Consumer
, Supplier
, etc.). Before Java 8, there were functional-like interfaces such as Runnable
, Callable
, and Comparator
, but Java 8 provided a formal structure for lambda expressions and functional programming. Additionally, libraries like Guava, Apache Commons, and Spring further expanded the list of functional interfaces for specialized use cases.
java.util.function
void accept(T t)
import java.util.function.Consumer;
public class ConsumerExample {
public static void main(String[] args) {
Consumer<String> printConsumer = str -> System.out.println(str);
printConsumer.accept("Hello, Consumer!");
}
}
Output: Hello, Consumer!
Supplier<T>
T get()
import java.util.function.Supplier;
public class SupplierExample {
public static void main(String[] args) {
Supplier<Integer> randomNumber = () -> (int)(Math.random() * 100);
System.out.println("Random number: " + randomNumber.get());
}
}
42
Predicate<T>
boolean test(T t)
import java.util.function.Predicate;
public class PredicateExample {
public static void main(String[] args) {
Predicate<Integer> isEven = num -> num % 2 == 0;
System.out.println(isEven.test(4)); // Output: true
System.out.println(isEven.test(5)); // Output: false
}
}
Output: