Posts

Showing posts with the label Java 8

Java: Collectors Class

Mastering Java 8's Collectors Class Introduction Java 8 introduced the Stream API, which revolutionized the way we process collections of data. One of the key components of this API is the Collectors class, which provides various methods to perform reduction operations on streams. In this blog post, we'll explore the Collectors class, its methods, and how to use them with practical code examples. What is the Collectors Class? The Collectors class is a final class that extends the Object class. It provides a variety of static methods that return instances of the Collector interface. These methods are used to perform mutable reduction operations on streams, such as accumulating elements into collections, summarizing elements according to various criteria, and more. Common Collectors Methods Let's dive into some of the most commonly used methods in the Collectors class: toList() toSet() toMap() ...

Java 8 IntStream Examples

In Java, `IntStream` is a part of the java.util.stream package and represents a stream of primitive integers. It's designed to work with the functional programming features introduced in Java 8, allowing you to perform aggregate operations on sequences of elements. Here are some examples of using `IntStream`: Example 1: Creating IntStream import java.util.stream.IntStream; public class IntStreamExample {     public static void main(String[] args) {         // Create an IntStream using range         IntStream.range(1, 6).forEach(System.out::println); // Prints 1, 2, 3, 4, 5                  // Create an IntStream using rangeClosed         IntStream.rangeClosed(1, 5).forEach(System.out::println); // Prints 1, 2, 3, 4, 5     } } Example 2: Operations on IntStream import java.util.stream.IntStream; public class IntStreamExample {     public static void ma...

Introduction To Functional Interface

Functional interfaces are a key feature introduced in Java 8 to support functional programming concepts. A functional interface is an interface that has exactly one abstract method. It serves as a contract for lambda expressions and method references, allowing functional-style programming in Java. In this in-depth analysis, we'll explore the characteristics, usage, and benefits of functional interfaces in Java. Characteristics of Functional Interfaces: 1. Single Abstract Method (SAM):  A functional interface should have only one abstract method. It can have any number of default or static methods, but only a single abstract method defines its functional nature. 2. Annotation:  The `@FunctionalInterface` annotation, introduced in Java 8, is optional for functional interfaces, but it serves as a documentation tool. It ensures that the interface remains functional by generating a compilation error if more than one abstract method is added. 3. Inheritance:  Functional interfa...

Java 8 parallelStream() vs. stream().parallel()

Introduction: In Java 8, the introduction of the Stream API revolutionized the way developers manipulate and process collections of data. Among its powerful features are the parallelStream() method and the parallel() method on regular streams. These methods enable concurrent processing, unlocking potential performance improvements in certain scenarios. In this blog post, we'll explore the differences between parallelStream() and stream().parallel(), along with their advantages and disadvantages. I. Understanding parallel processing: Before diving into the specifics of parallelStream() and stream().parallel(), let's briefly understand parallel processing. Parallel processing allows for concurrent execution of operations, potentially leveraging multiple threads to process data simultaneously. This approach can significantly enhance performance on multi-core systems, where workload distribution across cores leads to faster execution. II. The parallelStream() method: The paralle...

The Power of Java Optional

The Optional class was introduced in Java 8 to handle null values more elegantly. It is a container object which may or may not contain a non-null value. It provides a way to represent null values and also method to handle null values without throwing a NullPointerException. In this post, we will explore some common use cases of the Optional class. Avoiding NullPointerExceptions Before Optional, we had to do null checks like this: String name = getName(); if (name != null) {     int length = name.length();     // use length } With Optional, we can rewrite this as: Optional<String> name = Optional.ofNullable(getName()); if (name.isPresent()) {     int length = name.get().length();     // use length } This avoids the NullPointerException if getName() returns null. Default Values We can provide a default value if the Optional is empty using orElse(): Optional<String> name = Optional.ofNullable(getName()); String defaultName = "Default Nam...

Top 50 Java 8 Interview Questions For Senior Developer

Image
Hi guys, WELCOME TO JAVA INSPIRES. In this post, we will see top 50 java 8 interview questions for senior developers. 1. What is Java 8? Java 8 is a major release of the Java programming language that introduced several new features and enhancements to the platform. 2. What are the new features introduced in Java 8? Some of the key features introduced in Java 8 are: - Lambda expressions - Stream API - Default methods in interfaces - Optional class - Date and Time API (java.time package) 3. What are lambda expressions in Java 8? Lambda expressions are anonymous functions that can be treated as values and passed as method arguments. They simplify the syntax of writing functional interfaces and enable functional programming in Java. 4. What is a functional interface? A functional interface is an interface that contains only one abstract method. Java 8 introduced the `@FunctionalInterface` annotation to mark interfaces as functional interfaces. 5. How do you define a lambda expression i...

Java Program to Count the Occurrences of Each Character in String | Java Inspires

Image
Java Program to Count the Occurrences of Each Character in String In this post, we will write a simple java program to count the occurrences of each character in a given string. Here, first we will take a string and then create a character stream by spliting with "", and collect each character and count by grouping using java 8 stream features. package com . javainspires . examples ; import java.util.Arrays ; import java.util.LinkedHashMap ; import java.util.Map ; import java.util.function.Function ; import java.util.stream.Collectors ; public class ExampleMain { public static void main ( String [] args ) { String name = "Java Inspires Java Inspires" ; Map < String , Long > result = Arrays . stream ( name . split ( "" )) . collect ( Collectors . groupingBy ( Function . identity (), Collectors . counting ())); System . out . println ( res...

[Java 8 Examples] - Transforming a List

In this post, we will see how to transform a list object into different list using streams from Java 8 and Method references. Example #1: Convert all names to Upper case names in a List package java8examples; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * * @author #JavaInspires * */ public class Java8Example { public static void main(String[] args) { List<String> names = new ArrayList<String>(); names.add( "john" ); names.add( "Steve" ); names.add( "Lee" ); names.add( "Kent" ); names.add( "Robert" ); System.out.println(names); List<String> upperCaseNames = names.stream().map(String::toUpperCase).collect(Collectors.toList()); System.out.println(upperCaseNames); } } Output [john, Steve, Lee, Kent, Robert] [JOHN, STEVE, LEE, KENT, ROBERT]

[Java 8 Examples] How to remove all Null values from List using Java 8 Lamdas

 Hi Guys, Welcome to Java Inspires. In this post, we will see how to remove all Null values from a Java List using Java 8 Lamdas. package java8examples; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * * @author #JavaInspires * */ public class Java8Example { public static void main(String[] args) { // create a string list List<String> names = new ArrayList<String>(); // add elements names.add( null ); names.add( "John" ); names.add( null ); names.add( "David" ); names.add( null ); // print names list with null values System.out.println(names); // remove null values names.removeIf(Objects::isNull); System.out.println(names); } } Output [ null , John, null , David, null ] [John, David] About Objects class: public final class Objects extends Object This class consists of static utility methods for operating on objects. These utilities include null-safe or...

How to Convert java.util.Date to java.time.LocalDate

Image
Hi Guys, Welcome to Java Inspires. In this post, we will see the program how to convert java.util.Date object to java.time.LocalDate. Java8Example.java package com . javainspires . java8example ; import java.time.LocalDate ; import java.time.ZoneId ; import java.util.Date ; /** * * @author Java Inspires * */ public class Java8Example { public static void main ( String [] args ) { //create a data object Date date = new Date (); // print date System . out . println ( "Date date : " + date ); // convert date to LocalDate LocalDate localDate = date . toInstant (). atZone ( ZoneId . systemDefault ()). toLocalDate (); // print LocalDate System . out . println ( "LocalDate localDate : " + localDate . toString ()); } } Run the above program: Date date : Mon Apr 19 13:54:51 IST 2021 LocalDate localDate : 2021-04-19

How to get Common elements from two lists using Stream API filter()

Image
#JavaInspires  Hi Guys, Welcome to Java Inspires. In this post, we will see How to get Common elements from two lists using  Stream API filter(). Here, we will create two string lists with some common elements and will get common elements list by using filter method from stream api. Java8Example.java package com . javainspires . java8example ; import java.util.Arrays ; import java.util.List ; import java.util.stream.Collectors ; import java.util.stream.Stream ; /** * * @author Java Inspires * */ public class Java8Example { public static void main ( String [] args ) { // lets create two list with some common elements List < String > list1 = Arrays . asList ( "Arun" , "Kent" , "Rahul" , "Mathew" , "Clark" ); System . out . println ( "List 1 : " + list1 ); List < String > list2 = Arrays . asList ( "Kent" , "Rahul" , "Robert" ...

Java 8 Streams filter() - Simple Example

Image
#JavaInspires 😀 Hi Guys, Welcome to Java Inspires. In this example, we will see how to use filter method from Java 8 streams. Here, we will create a employee list and filter the same with employee age greaterthan 30. Java8Example.java package com . java inspires . java8example ; import java.util.ArrayList ; import java.util.List ; import java.util.stream.Stream ; /** * * @author Java Inspires * */ public class Java8Example { public static void main ( String [] args ) { // create employee list List < Employee > employees = new ArrayList < Employee >(); // add employees to the list employees . add ( new Employee ( "E101" , "John" , 22 )); employees . add ( new Employee ( "E102" , "Steve" , 28 )); employees . add ( new Employee ( "E103" , "William" , 37 )); employees . add ( new Employee ( "E104" , "Clark" , 32 )); employee...