الاثنين، 24 أغسطس 2020

Java 8 Optional Tutorial With Examples

1. Overview

In this tutorial, You will learn in-depth about Java 8 Optional Class methods and its usages.

Optional class is added to the java.util package. The intention of introducing this class in java 8 is mainly to check whether the value is present in the object or it is absent.

The object is to hold the set of values that means it contains the real values. So, such kind of object is called a Container.

The container object may contain a null or non-null value in it.

Java 8 Optional Tutorial With Examples

الأربعاء، 19 أغسطس 2020

Java 8 Base64 Encoding and Decoding (With Examples)

1. Overview

In this article, you'll learn the different ways to do the base 64 encoding and decoding techniques in java 8 and other alternative libraries such as apache common API utility.

Main focus on How to do Base64 encoding and decoding in Java, using the new APIs introduced in Java 8 as well as Apache Commons.

Understand the techniques on how to encode and decode base64 in java.

Java 8 Base64 Encoding and Decoding (With Examples)

الثلاثاء، 18 أغسطس 2020

How to remove all duplicates from a List in Java 8?

1. Overview

In this article, you'll explore the different ways to clean up and remove duplicates from the list and ArrayList.

Let us see the example programs using plain java and java 8 stream api lambda expressions.


2. Removing Duplicates Using Plain Java

A simple way is to remove the duplicates to clean up the list using List.contains() method. Create a new list and Pass every value of the original list to the contains() method on a new list. Returns false if the current value is not present in the new list and add the value to the new list. if returns false means that value is already present in the list and skip the value-adding to the new list.

Example:

import java.util.ArrayList;
import java.util.List;

public class RemoveDuplicatesContains {

	public static void main(String[] args) {

		// Creating a new list
		List<String> originalList = new ArrayList<>();
		
		// Adding duplicate values
		originalList.add("A");
		originalList.add("B");
		originalList.add("C");
		originalList.add("C");
		originalList.add("B");
		originalList.add("A");
		
		// printing the original list
		System.out.println("Original list values : "+originalList);
		
		// created a new list to add only unique values
		List<String> newList = new ArrayList<>();
		
		// filtering the duplicates from the 
		originalList.forEach(eachValue -> {
			if(!newList.contains(eachValue)) {
				newList.add(eachValue);
			}
		});
		
		// printing the cleaned list without duplicatesa
		System.out.println("newlist values are : "+newList);

	}
}

Output:

Original list values : [A, B, C, C, B, A]
newlist values are : [A, B, C]

3. Removing Duplicates Using LinkedHashSet

Next, use LinkedHashSet to remove the duplicates and preserve the order as in the original list. LinkedHashSet is a collection api Set interface. Set interface implementation such as HashSet or LinkedHashSet. But, many developers use HashSet rather than LinkedHashSet.

Example:

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicatesLinkedHashSet {

	public static void main(String[] args) {

		// Creating a new list
		List<String> originalList = new ArrayList<>();

		// Adding duplicate values
		originalList.add("A");
		originalList.add("B");
		originalList.add("C");
		originalList.add("C");
		originalList.add("B");
		originalList.add("A");

		// printing the original list
		System.out.println("Original list values : " + originalList);

		// Creating linkedhashset object
		Set<String> linkedSet = new LinkedHashSet<>();

		// adding list values to set
		linkedSet.addAll(originalList);

		// removing all values from list
		originalList.clear();

		// add all values from set to list.
		originalList.addAll(linkedSet);

		// printing the cleaned list without duplicates
		System.out.println("originalList values ater removing duplicates  : " + originalList);

	}
}

Output:

Original list values : [A, B, C, C, B, A]
originalList values ater removing duplicates  : [A, B, C]

4. Remove Duplicates From a List Using Java 8 Lambdas

Let us look at the new JDK 8 lambda expressions and Stream api's distinct() method to remove duplicates.

distinct() method internally calls equals() method on each value and filters the duplicates objects.

In our example, we are adding Strings to the list so equals() method of String class will be called. If you are passing the Custom objects then you need to override the equals() method in the custom class as per needed.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class RemoveDuplicatesJava8Distinct {

	public static void main(String[] args) {

		// Creating a new list
		List<String> originalList = new ArrayList<>();

		// Adding duplicate values
		originalList.add("A");
		originalList.add("B");
		originalList.add("C");
		originalList.add("C");
		originalList.add("B");
		originalList.add("A");

		// printing the original list
		System.out.println("Original list values : " + originalList);

		// Java 8 Stream API - distinct() method used
		originalList = originalList.stream().distinct().collect(Collectors.toList());

		// printing the cleaned list without duplicates
		System.out.println("Removed duplicates with java 8 api : " + originalList);

	}
}

Output:

Original list values : [A, B, C, C, B, A]
Removed duplicates with java 8 api : [A, B, C]

5. Conclusion

In this article, you've seen the 3 different ways to remove all duplicates from ArrayList with examples programs.

All are over GitHub.

distinct example

Java 8 Stream concat() - How To Merge Two Streams or More

1. Overview

In this article, you are going to learn the java 8 Stream api concat() method to merge two streams into one stream. In the end, merged streams or collections will have all elements from both streams.

Let us explore the different ways to merge the streams using java 8 stream api.

Java 8 Stream concat() - How To Merge Two Streams or More

الاثنين، 17 أغسطس 2020

Java 8 Stream limit() Method Example

1. Overview

In this article, you'll learn how to limit the stream elements to the given size even though it has more elements.

Use Java 8 Stream.limit() method to retrieve only the first n objects and setting the maximum size. And it ignores the remaining values after size n. Stream.limit(long maxSize) returns a Stream of objects.

We will explore the different ways to do limit the stream using the limit() method and how to limit the collection elements based on a condition?

Java 8 Stream limit() Method Example

الأحد، 16 أغسطس 2020

Spring Boot Scheduling Tasks With @Scheduled Annotation

1. Introduction

In this tutorial, We'll learn how to run scheduled jobs in Spring Boot. There are some scenarios, you need to perform some tasks periodically at a fixed interval of time. Spring boot provides mainly with @Scheduled fixedRate and fixedDelay attributes.

In fact, Spring Boot bundled with two annotations those support scheduling at a given time.

@EnableScheduling and @Scheduled annotations do the job in spring boot. 

First, @EnableScheduling should be applied to the SpringBootApplication.
Next, @Scheduled must be applied on any method but that method should not take any arguments and should not return any value hence void should be return type.


Spring Boot Scheduling Tasks Examples - @Scheduled fixedRate Vs fixedDelay


Java 8 Stream skip() Examples

1. Overview

In this article, You'll learn how to use stream skip() method of java 8 and how to skip the first n objects from stream.

Java 8 Stream skip() Examples

Java 8 – Sorting Stream On Multiple Fields with Comparator.thenComparing()

1.Overview

In this tutorial, You'll learn how to sort the collection or stream of objects on multiple fields in java 8.

In the previous article, I have shown how to implement custom sorting using Collections.sort() method.

Java 8 – Sorting Stream On Multiple Fields with Comparator.thenComparing()

Java 8 forEach Examples on List, Set and Map

1. Overview

In this tutorial, We'll learn how to use forEach method which is introduced in Java 8.

We will work on forEach examples before and after java 8 on List and Map.

Java 8 made a revolution to support Functional programmings such as using Streams and Functional Interfaces.

A Stream can be created for any collection such as from List, Set and Map. Stream API also has a method named forEach() to iterate collection in sequential and parallel mode. This stream for each very effective. We will be showing the examples on each.

Java 8 forEach Examples


All Collection classes implement the Iterable interface which has forEach() method. This forEach() method is a default method in it and can be invoked on every collection class such as ArrayList, Hashset, Treeset.

But, the Separate forEach(BiConsumer biConsumer) method is implemented in the Map interface as the default method. This is invoked on any Map implementation such as HashMap, TreeHashMap, and LinkedHashMap.

Java 8 – Convert Map to List (HashMap to ArrayList)

1.Overview


In this article, You'll learn how to convert Map to List in java and Stream API examples in java 8.

Let us explore the different ways to convert HashMap to ArrayList.

ArrayList is to store the objects in insertion order and allow duplicates

HashMap is a collection that is used to store the key/value pairs.

Java 8 – Convert Map to List (HashMap to ArrayList)

السبت، 15 أغسطس 2020

Java 8 and Infinite Streams - How To Create Infinite Streams

1. Overview

In this article, You'll learn how to create infinite streams and how to use them in java 8.

Use Stream.iterate() and Stream.generate() method to create infinite streams in java. These two are declared as static methods and these are called utility methods.

Before diving into the Infinite Stream concepts, Let us understand the few concepts such as Intermediate and Terminal operation from Stream API.

Java 8 and Infinite Streams - How To Create Infinite Streams

الجمعة، 14 أغسطس 2020

A Guide to Streams in Java 8: In-Depth Tutorial With Examples

1. Stream API Overview

In this tutorial, We'll take a look at an in-depth tutorial with examples on Java 8 Stream API.

Java 8 introduced a new API which is called as Stream. This API supports processing the large data sets in a sequential and parallel model.
When we see the code that looks to the SQL query database.

Before that, you can take a look at the Java 8 Lambda Expression Rules to write the errorless code.

Java 8 Stream API Introduction


we'll learn about java 8 in the aspect of the following.


  • Impact of Multi-Core CPU
  • Anonymous Inner classes
  • Stream Pipe Line
  • Functional Interfaces
  • How java 8 code looks with Examples

الخميس، 13 أغسطس 2020

How To Convert ArrayList To String Array In Java 8 - toArray() Example

1. Overview

In this article, You're going to learn how to convert ArrayList to String[] Array in Java. ArrayList is used to store the List of String using the toArray() and Stream API toArray() method.

How To Convert ArrayList To String Array In Java 8 - toArray() Example

Inheritance in Java, Inheritance Types with Examples

1. Inheritance in Java:

We will guide you to learn what is Inheritance in Java with examples, What are the Types of Inheritance, What is the significance of super keyword in it, Advantages, Disadvantageous. .

Inheritance is one of the core principle of OOPS concepts. Inheritance provides the facility to acquire one class properties such as instance variables and methods by another class.


In Java, It is impossible to write a class without using Inheritance concept. Every class by default inherits the fields and method of Object class.


Inheritance in Java, Inheritance Types with Examples

Understanding public static void main (String[ ] args)) in Java

1. Overview


In this tutorial, We'll understand each term in public static void main(String[] args) method in java.

public static void main() is called as psvm sometimes.

In Java, public static void main plays a vital role in running applications and important topic in SCJP or OCA certification exam.

we will discuss now the following in this post.


Java public static void main(String[ ] args)) method usage, Rules, Example, Interview Questions


We will discuss in-depth in the following areas.
Rules
Explanation of each keyword
Examples
Real-time scenario
Negative cases.
What will happen if we apply different keywords
Interview questions.
Summary 

الأربعاء، 12 أغسطس 2020

Raw type Generics in Java - Working Examples

1. Raw type Generics in Java 


Raw Type is part of Java Generics. Raw Type is If any generic class reference or instance is created without mentioning the proper Type for the Generic type. Reference indicates to Class or Interface.

Generics in Java

Generics naming conventions and rules

Generics main aim to provide tighter type checks at compile time.

Raw type in Java Generics with Examples

Java Program to Optimized Bubble Sort With Examples

1. Optimized Bubble Sort in Java

In this post, we will learn how to optimize the bubble sort algorithm. This is a very basic interview question in many product-based companies for freshers and 0-2 experience.

Of course, Bubble Sort is one of the slowest algorithms but still, we can optimize it for better performance and this is only for smaller sets of input.

If you do not know the bubble sort algorithm and how it works then please go through the below article for a better understating of optimization.


Java Program to Optimized Bubble Sort With Examples



How to create a dictionary in Java - Java.util.Dictionary Examples

1. Overview

In this article, You will learn in-depth about the Dictionary class in java and how to create a dictionary in java?

Dictionary is an abstract class in java api which used in collections such as Hashtable. Dictionary supports backend to store the values as key, value pair. Key and Values are should be objects.

In Dictionary, Every key value must be having a value that can be a null or non-null object and keys are not stored in the insertion order. This does not allow duplicate keys.

Since the dictionary is an abstract class so, we can not create an object for it. Hence, object creation is possible to only its implementation classes. As a rule, the equals method should be used by implementations of this class to decide if two keys are the same.

How to create a dictionary in Java - Java.util.Dictionary Examples


Java For loop Examples - Nested For Loop Examples

For Loop in Java:

In java, for-loop has two versions.

1) Basic for loop (Old style)
2) Enhanced for loop (For-each or for-in loop)


First, we will discuss basic for loop then next discuss Enhanced loop.
The enhanced loop is designed mainly for Arrays or Collection. We will discuss this in the next tutorial.

Enhanced for loop and Examples.

Java For loop, Examples

Basic for loop:

The basic loop has the flexibility to use it as per our needs. This is very useful if we know how many times it needs to be executed.

It has three sections.

1) Variable declaration and its initialization
2) Condition: Untill condition is true, the loop will be executed.
3) Variable increment/decrement

الثلاثاء، 11 أغسطس 2020

How To Set All values of Array To Same Value In Faster Way?

1. Overview

In this article, You will learn how to set or fill the all values of the array with a single value in a faster way. This is quite interesting to do but very easy.

In the previous article, I have shown how to create and initialize the array with values.

And also will show the example program to create an array with n copies of the same value/object using Arrays.fill() method.

How To Set All values of Array To Same Value In Faster Way?

الاثنين، 10 أغسطس 2020

Kotlin Program to Sort ArrayList of Custom Objects By Property

1. Introduction


In this tutorial, you will learn how to sort the ArrayList of Custom objects and sort by their given property or field.

This is part of the Kotlin Programming Series.

First, We will see the example program to sort the custom class and next, how to sort the List of Employee objects.

Kotlin Program to Sort ArrayList of Custom Objects By Property

Spring Framework BeanDefinitionRegistryPostProcessor Example

1. Introduction


In this tutorial, You'll learn about BeanDefinitionRegistryPostProcessor interface in Spring and Spring Boot.

Spring Framework API - BeanDefinitionRegistryPostProcessor is used to register the bean dynamically with application context at runtime. This is most useful in the realtime when working with client libraries those are changed frequently. By using this bean, you can reduce the deployments of the application but you should use this with care. Otherwise, It will override the existing bean configuration.

Spring BeanDefinitionRegistryPostProcessor interface has one abstract method "void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException".

This is mainly useful if you have any third-party libraries which are not spring beans. So, these beans can be registered dynamically at runtime based on your need.

BeanDefinitionRegistryPostProcessor is also one of the interfaces to register the beans at runtime without using @Bean or @Component annotations in the program.

Spring Framework BeanDefinitionRegistryPostProcessor Example


From API:

Extension to the standard BeanFactoryPostProcessor SPI, allowing for the registration of further bean definitions before regular BeanFactoryPostProcessor detection kicks in. In particular, BeanDefinitionRegistryPostProcessor may register further bean definitions which in turn define BeanFactoryPostProcessor instances.

Spring Boot BeanDefinitionRegistryPostProcessor


So, Any classes that implement the BeanDefinitionRegistryPostProcessor interface will be executed before the start BeanFactoryPostProcessor registration.

الأحد، 9 أغسطس 2020

الأربعاء، 5 أغسطس 2020

How to Add delay in Java for sometime?

1. Overview


In this article, You'll learn how to delay the code execution for some seconds or minutes in java. This quite simple and easy to force the code to sleep or pause for some time and do the remaining execution or waiting for another task to complete.

You might be seeing this is needed when you have any failures or connectivity issues in the application then immediately you don't want to execute tasks. So, You must have to wait for sometime before running the same task.

This is a common use case in every realtime application.

Let us explore the different ways to do the delay in java.

How do I make a delay in Java? Pausing Execution with Sleep

السبت، 1 أغسطس 2020

Java 8 Iterable.forEach() vs foreach loop with examples

1. Overview


In this article, you'll learn what are the differences between the Iterator.forEach() and the normal foreach loop before java 8.

First, let us write a simple program using both approaches then you will understand what you can not achieve with the java 8 forEach.

Iterable is a collection api root interface that is added with the forEach() method in java 8. The following code is the internal implementation. Whatever the logic is passed as lambda to this method is placed inside Consumer accept() method. Just remember this for now. When you see the examples you will understand the problem with this code.
default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
Java 8 Iterable.forEach() vs foreach loop with examples