الثلاثاء، 30 نوفمبر 2021

[Fixed] Another git process seems to be running in this repository git in 6 ways

1. Overview

In this article, We'll learn how to fix the git error "Another git process seems to be running in this repository" in windows and mac operating systems.

When you are a beginner or working a git project, you get this type of error.

This error is saying git commands are locked by another git process for the current git application. Somewhere you are running two git commands at the same time. Simultaneous execution of git commands lead to error - Another git process seems to be running in this repository.

Another git process seems to be running in this repository


[Fixed] Git error: failed to push some refs to in 5 ways

1. Overview

In this tutorial, We'll learn how to fix the git error failed to push some refs to in 5 ways.

Most of the time you get this error while pushing your change git remote repository.

This might be working a few days back but suddenly started showing a weird error message "failed to push some refs to".

You are stuck at this point and do not what to do now. And you might be thinking because of my new changes?


For this error, there are mainly two reasons.

a) Your branch is set to main and not master
b) Remote repo has new changes and you do not have those changes on your laptop or local branch

Now, you knew about the actual reasons to get this common error.

Let us jump into the fixes.

Git error: failed to push some refs to

[Fixed] fatal: not a git repository (or any of the parent directories): .git in 2 ways

 

1. Overview

In this tutorial, We'll learn how to fix git error "fatal: not a git repository (or any of the parent directories): .git" on windows or mac os or Heroku.

Fixing this error can be done in 2 ways. But first, let us understand the error what is the meaning of the error.


fatal not a git repository (or any of the parent directories) .git

Java PrintWriter

1. Overview

In this tutorial, We'll learn how to use PrintWriter class in java with examples.

PrintWriter class is present in a package of java.io and PrintWriter class is an implementation of Writer class.
public class PrintWriter
extends Writer

PrintWriter class is used to store or print the formatted representation of the object to the next output stream.


This class implements all methods from PirntStream class.

None of the methods from PrintWriter class does not throw IOException. But some of the contractors may throw IO Exceptions.

To know the errors are present or not, we need to use the checkError() method.

It is not possible to use PrintWriter with Java 8 Streams.

Java PrintWriter

الاثنين، 29 نوفمبر 2021

How To Enable HSTS Header? How to Implement custom HSTS Filter in Java with Examples?

1. Overview:

In this post, We'll learn how to enable/add HTTP Strict Transport Security (HSTS) Header to Tomcat 8 using a built-in filter. And also discuss how to add a custom HSTS filter in a java web application.

Learn Enabling/Adding HTTP Strict Transport Security (HSTS) Header to a Website in Tomcat or Any Server


As well as a solution to add HSTS to any web-site using web.config.

At last, will talk about the testing methodology to make sure HSTS is enabled for a website.

About HSTS:


HTTP Strict Transport Security (HSTS) instructs web browsers to only use secure connections for all future requests when communicating with a website. Doing so helps prevent SSL protocol attacks, SSL stripping, cookie hijacking, and other attempts to circumvent SSL protection.

Enabling HSTS Header

[Fixed] Git - remote: Repository not found in 9 ways (Windows and Mac)

1. Overview

In this tutorial, we'll learn how to fix the "Git - remote: fatal Repository not found" issue in 9 different ways.

You might have seen this error while cloning the repository or while pushing the commits to the remote repository.

This error can be fixed in simple ways.

[Fixed] Git - remote: Repository not found



2. Fix 1 - Git - remote: Repository not found


If you are new to programming and developing then you might have not set remote repo URL on your local repo. And trying to push the changes to remote.

This is needed when you downloaded the project as a zip file.

In this case, you need to set the remote base url to the local repo using the "git remote" command.

More on Git Commands

Follow the below steps.

git remote set-url origin https://github.com/JavaProgramTo/Kotlin-Demo.git

git add *.java
git commit -m "commit title"
git push origin master


3. Fix 2 - Git - remote: Repository not found


If the above is not your case, then you need to make sure that the remote URL is the correct one is pointing out.

Use git remote command as below.

git remote -v
origin	https://github.com/JavaProgramTo/Kotlin-Demo.git (fetch)
origin	https://github.com/JavaProgramTo/Kotlin-Demo.git (push)

If it is showing the right URL then verify it on remote whether it is the correct one or not. If not the correct one then you need to follow fix 1 to set the correct remote repo.


4. Fix 3 - Git - remote: Repository not found


Verify if your password has been reset recently. If you have changed so please make sure the new password is fetched from the credential manager on windows or keychain access on mac.

Sometimes, an old password will be used and a new one is not cached yet.

In this case, Remove all github.com credential details from the system. 
you need to clear the git related info from the credential manager and remove it from keychain access.

On windows

Follow the below commands on windows. After this, you should be able to push and pull the changes.
$ git credential-manager uninstall

$ git credential-manager install


On Mac machine

Open Keychain Access and find your password account in the password category ( you can search it on the top right keychain access page)

Once you find it, delete all keys related to your git source control and then try it again from the clone.

Before this take the backup of your uncommitted changes.


5. Fix 4 - Git - remote: Repository not found


This is a temporary fix and not recommended for the long term.

On Windows

  • Go to the git folder and go inside the .git folder
  • Open 'config' file using notepad or any other editor
  • Change your URL from https://github.com/username/repo_name.git to https://username:password@github.com/username/repo_name.git
  • Save and Push the code, it will work.
Here, you need to save the password and security threat.

On Mac

If the GitHub entry is not present in keychain access then you can clone the app in a different way as below.
git clone https://username@github.com/org/repo.git

Follow the below steps.

  • username with your GitHub username
  • org with your organisation name
  • repo with the repository name

6. Fix 5 - Git - remote: Repository not found


Just run the git remote update command which updates the local repo with the remote repo and its credentials.

If this command is executed without any issues then your issue will be resolved.
git remote update


7. Fix 6, 7, 8, 9- Git - remote: Repository not found


There might be chances of any one of the following.

7.1 If you are not a collaborator, then you may successfully authenticate the GitHub but can not clone or push the changes to the repository as long you are not a collaborator.

7.2 In case of any spelling issues

7.3 If the git remove -v has set to HTTPS but your repo is pointing to the ssh. In this case, you need to remove the ssh and add HTTPS.

git remote remove origin
git remote add origin https://github.com/JavaProgramTo/Kotlin-Demo.git

7.4 Remote repository is not found and deleted.


8. Conclusion


In this article, we've seen all versions of fixes on git error "fatal: repository not found error".


Git Delete Local Branch and Remote Branch (With Force Delete)

1. Overview

In this tutorial, We'll learn how to delete the local branch and remote branch in git with normal and force delete options.

Git provides easy access and manages the git local branches. And also provides exceptional support to remove local branches without any exception.

Removing git local branches can be done in two ways and removing remote repo in one way with commands.

Git Delete Local Branch and Remote Branch



let us look one by one now.

It is very useful to know Git Commands.

How to create and initialize boolean array in java?

1. Overview

In this tutorial, We'll how to use boolean array and how to initialize boolean array in java.

Boolean array is used to store the only boolean values. boolean value can be either true or false.

The default value of boolean type is false and the default value of the primitive boolean array is false for all indexes.

Boolean array references are initialized with null values.

In some cases, the default value is false is not useful. To make the default value true, we need to use the Arrays.fill() method.

How to create and initialize boolean array in java?

الأحد، 28 نوفمبر 2021

Java 8 Stream map() examples - Stream Conversions

1. Overview


In this article, we'll be learning about a new map() function in Java 8 that is introduced in Stream API. map() method converts a Stream from one form to another Stream. This takes input X type Stream and converts into Y type output Stream.

This is widely used as part of new JDK 8 api.

Java 8 Stream map() examples - Stream Conversions


السبت، 27 نوفمبر 2021

Java Nested Arrays - Multidimensional Arrays Examples

1. Overview

In this article, We'll learn how to create and access nested or multidimensional arrays.

Example programs on single, 2D and 3D dimensional arrays in java.


Java Nested Arrays - Multidimensional Arrays Examples

Java HashSet class with Examples, Usage

Java Collection API HashSet Class


In Java, HashSet is defined as class and introduced in version 1.2 as part of Collection api. It is available in package java.util.HashSet.

HashSet is implemented based on Set interface to not allow duplicate values.

Java-Hashset


Java Set to String

1. Overview

In this tutorial, We'll learn how to convert Set to String in java with examples.

Example programs on HashSet<String> to String and LinkedHashSet<String> to String.

And also HashSet<Integer> to String with Java 8 Stream api methods.

Java Set to String

Java - Create and Iterate List of Lists With Examples

1. Overview

In this tutorial, We'll learn how to create the List of Lists and iterate them in java and the newer java 8 version with simple example programs.


This is like List is holding another list of strings or list of integers or in some cases it can be user-defined custom objects.

Let us look at each type of object creation and loop through them in java.

Java - Create and Iterate List of Lists With Examples

Nested lists with streams in Java 8 With flatMap() (list of lists)

1. Overview

In this article, You're going to learn how to work with nested list with java 8 streams.

Java 8 Stream API is added with flatMap() method which has the capability to map + flatten into objects or actual values.

let us explore more ways using flatMap() with complex objects to work with a list of lists or collection of collections.

In our example, we are using a List of objects but you can use List or Set implementations.

Nested lists with streams in Java 8

الجمعة، 26 نوفمبر 2021

Java - Converting between List and Set (6 ways)

1. Overview

In this article, We'll learn how to convert between List and Set objects. First, start with the basic java API methods, JDK 8 and above.

Finally, we'll learn how to convert List to Set and Set to List using Guava and apache commons API's.

In the previous article, we have discussed the conversion between List and Map objects.

Java - Converting between List and Set (6 ways)

Java 8 Streams - Join or Append Stream of Strings using Collectors.joining()

1. Overview

In this tutorial, We'll learn how to append or join a list of strings or stream of strings in java 8.

This joining is done with a specific delimiter or separator with the Collectors api method.

Use Collectors.joining() method joins the values of the stream with a delimiter specified. If the delimiter is not specified then it takes nothing as a separator. So, that final returned string will be having just all values concatenated from the stream.

Along with the joining, this method does the conversion from java 8 stream to string object with the default delimiter.

Java 8 Stream Join String


2. Collectors.joining() Method


Collectors.joining() method does concatenate the list of values or list of strings or stream of values or strings into a new string. 

For this method, we can pass the our own delimiter and and also we can supply the prefix, suffix to the output string.

joining() is an overloaded method and available in 3 versions.

public static Collector<CharSequence,?,String> joining()
public static Collector<CharSequence,?,String> joining(CharSequence delimiter)
public static Collector<CharSequence,?,String> joining(CharSequence delimiter,
                                                       CharSequence prefix,
                                                       CharSequence suffix)


joining(): Input elements are concatenated into a new String as encounter order in the stream.

joining(CharSequence delimiter): Input elements are concatenated into a new String with the given delimiter value as encounter order in the stream.

joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix): Input elements are concatenated into a new String with the given delimiter, suffix and prefix values as encounter order in the stream.


3. Java 8 Stream Join String Examples


Next, let us write the example programs using all these 3 methods of Collectors.joining().

Below example program does the stream joining as string and converting stream to string.

package com.javaprogramto.java8.streams.join;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Java Join Stream Of Strings and stream to string examples.
 * 
 * @author JavaProgramTo.com
 *
 */
public class StreamOfStringJoiningExample {

	public static void main(String[] args) {

		// Creating the List with string values using Arrays.asList() method
		List<String> stringsList = Arrays.asList("1", "2", "3", "4", "5");

		// java 8 join stream of strings or stream to string

		// Example - 1: with default delimiter
		String joinWithDefaultDelimiter = stringsList.stream().collect(Collectors.joining());

		// Example - 2: with delimiter
		String joinWithDelimiter = stringsList.stream().collect(Collectors.joining(":"));

		// Example - 3: with given delimiter, suffix and prefix
		String joinWithDelimiterSuffixPrefix = stringsList.stream().collect(Collectors.joining("|", "[", "]"));

		// printing the values
		System.out.println("Input List of strings : " + stringsList);
		System.out.println("joining() string : " + joinWithDefaultDelimiter);
		System.out.println("joining(delimiter) string : " + joinWithDelimiter);
		System.out.println("joining(delimiter, suffix, prefix) string : " + joinWithDelimiterSuffixPrefix);
	}
}

Output:
Input List of strings : [1, 2, 3, 4, 5]
joining() string : 12345
joining(delimiter) string : 1:2:3:4:5
joining(delimiter, suffix, prefix) string : [1|2|3|4|5]

From the output, we can observe the output from 3 methods with default delimiter, custom delimiter and with a prefix and suffix values.


4. Stream IllegalStateException: stream has already been operated upon or closed


In the above program, we have created the new stream every time we call collect() or joining() method. You may think, can we reuse the stream object for the next two calls. Thats mean first create the Stream object once using stream() method and use the same stream object for all joining() calls.

Look the below code and the output.

		// Creating the stream object once and reuse for every collect() call.
		Stream<String> stream = stringsList.stream();

		// java 8 join stream of strings or stream to string
		
		// Example - 1: with default delimiter
		String joinWithDefaultDelimiter = stream.collect(Collectors.joining());

		// Example - 2: with delimiter
		String joinWithDelimiter = stream.collect(Collectors.joining(":"));
		
		// Example - 3: with given delimiter pipe(|), suffix and prefix
		String joinWithDelimiterSuffixPrefix = stream.collect(Collectors.joining("|", "[", "]"));


Output:

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:229)
	at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
	at com.javaprogramto.java8.streams.join.StreamOfStringJoiningExample.main(StreamOfStringJoiningExample.java:29)

We got the runtime exception because once the terminal method collect() is called stream will be closed. In the next step, we are trying to call collect() method on the closed stream.

We have already discussed in detail about the error "stream has already been operated upon or closed" and how can be handled using Supplier.


5. Conclusion


In this article, We've seen how to join the stream of strings and how to convert Stream to String in java 8 with help of the joining() method.




Ref 

Java 8 - Convert IntStream to String

1. Overview

In this tutorial, We'll learn how to convert IntStream into String value in java 8.

In previous tutorials, we have seen how to convert IntStream to List and IntStream to Array using stream API methods.

Java 8 - Convert IntStream to String

Java 8 - Convert IntStream to Array

1. Overview

In this tutorial, We'll learn how to convert IntStream to Array of ints in java 8.

IntStream is used to create infinite streams with the number series pattern.

But, some of the time we might need to convert the number series to an array.

Java 8 - Convert IntStream to Array

Java 8 - Convert IntStream To List and Other

1. Overview

In this tutorial, We'll learn how to convert IntStream to List in java 8 and java 16 above versions.

IntStream is used to create the infinite streams in java 8 and it has the method to convert it to array using toArray() method.

But there are no other methods to directly convert it to List or set.

Conversion of IntStream to List can be done in two ways.

Java 8 - Convert IntStream To List and Other

Java 8 Stream reduce

1. Overview

In this tutorial, We'll learn how to use reduce() method to produce the final result from the stream in java 8.

Stream API is added in java 8 and now reduce operation is heavily used by the developers.

reduce() method is a terminal operation of streams.

Java 8 Stream reduce


الخميس، 25 نوفمبر 2021

Java 8 – Convert LocalDateTime to Timestamp & Vice Versa

1. Overview

In this tutorial, We'll learn how to convert LocalDateTime object into the Timestamp in java 8 new Date Time API.

If you are new to Java 8 or above, It is recommended to read java 8 new date-time API in java indepth 

And also we will learn how to convert LocalDate to TimeStamp in java 8.

Java 8 – Convert LocalDateTime to Timestamp & Vice Versa

Java 8 Integer Class new methods

1. Overview

In this tutorial, We'll learn what are the new methods added to the Integer class in Java 8.

Below are the new methods of integer class and look at each example to understand its usage.

All methods are static and access directly with class name. All unsigned methods work for positive and negetive integer values.

Java 8 Integer Class new methods


public static String toUnsignedString(int i, int radix)
public static String toUnsignedString(int i)
public static int parseUnsignedInt(String s, int radix) throws NumberFormatException
public static int parseUnsignedInt(String s) throws NumberFormatException
public static int hashCode(int value)
public static int compareUnsigned(int x, int y)
public static long toUnsignedLong(int x)
public static int divideUnsigned(int dividend, int divisor)
public static int remainderUnsigned(int dividend, int divisor)
public static int sum(int a, int b)
public static int max(int a, int b)
public static int min(int a, int b)

الأربعاء، 24 نوفمبر 2021

Java Convert String To int - Parse Examples

1. Overview

In this tutorial, We'll learn how to convert string to int in java

Let us explore the different ways to convert a string to an integer value using various methods from java built-in API.

This is very common in software life. We need to represent the string that contains numbers into the integer type.

Example:

Input String = "12345";
Output int = 12345;

In Java, we can convert String to int using Integer.parseInt(), Integer.valueOf(), Integer constructor and DecimalFormat.parse(string).intValue() methods and these methods returns integer object.

Java Examples - Convert String To int


2. String to Int: Using Integer.parseInt()


parseInt(String string) method is static method and it is present in Integer class.This method converts the given string into integer number. If the given string contains at least non digit then it will throw the runtime error NumberFormatException.

public class ParseIntExample 
{
    public static void main(String[] args) 
    {
		// Creating a string
        String s = "12345";
		
		// converting string to int using parseInt() method
        int i = Integer.parseInt(s);
		
		// printing the input and output
        System.out.println("string : "+s);
        System.out.println("integer : "+i);
    }
}

Output:

string : 12345
integer : 12345

3. String to Int: Using Integer.valueOf()


Next, use valueOf(String s) method to convert String object to an int value. But this method also works as similar to the parseInt() method.

But the main difference between parseInt() and valueOf() method is parseInt() method returns primitive int and valueOf() method returns wrapper Integer object.

public class ValueOfExample
{
    // Example to string to int
    public static void main(String[] args) 
    {
		// Creating String object with value "1000"
        String s2 = "1000";
		
		// Calling valueOf() method which does string to int conversion
        Integer i2 = Integer.valueOf(s2);
		
		// printing values
        System.out.println("string value: "+s2);
        System.out.println("integer value: "+i2);
    }
}

Output:

string value: 1000
integer value: 1000

4. String to Int: Using Integer Constructor with String Argument


Next, Look at another approach which does use constructor of Integer class with string type as an argument as new Integer("2468");

public class IntegerConstructorExample
{
	// string to int with integer constructor
    public static void main(String[] args) 
    {
		// creating string object 3
        String s3 = "999";
		
		// convert string to integer with Interger constructor
        Integer i3 = new Integer(s3);
		
         // convert Wrapper integer to primitive int using primitive int
        int int3 = i3.intValue();
		
		// printing the values
        System.out.println("String s3 value : " + int3);
        System.out.println("Integer int3 value : " + int3);
    }
}

Output:

String s3 value : 999
Integer int3 value : 999

5. String to Int: Using DecimalFormat class


The final approach is, Use DecimalFormat.parse() method with string as an argument. Pass value "0" to DecimalFormat class constructor so that it treats only the numbers as input.

Next, call parse() and pass the string value to be converted into an int value. parse() method returns Number object and needs to get the int value from intValue() method from Number class.

Example:

import java.text.DecimalFormat;
import java.text.ParseException;

public class DecimalFormatExample 
{
    // DecimalFormat.parse() example to parse string into int value.
    public static void main(String[] args) throws ParseException 
    {
		// Creating a string object with value 123456
        String string = "123456";

        // Passing "0" to the DecimalFormat indicates that it shuould accepts only digits.
        DecimalFormat decimalFormat = new DecimalFormat("0");

        // parsing String to Number
        Number number = decimalFormat.parse(string);
     
        // converting Number to primitive int.
        int i4 = number.intValue();

		// printing values
       System.out.println("string value : " + string);		
       System.out.println("i4 value : " + i4);
    }
}

Output:

string value : 123456
i4 value : 123456

6. String To Int Exception Java


If the input string literal is having the non numeric characters and call Integer class parseInt() or valueOf() or constructor or DecimalFormat class methods will end up in runtime exception "NumberFormatException".

package com.javaprogramto.convert.string.toint;

/**
 * Example to exception in string to integer conversion
 * 
 * @author Javaprogramto.com
 *
 */
public class StringToIntException {

	public static void main(String[] args) {

		// creating string with alphabets
		String s = "hello world";

		// convert string to int using parseInt() method. This will throw exception
		// int number = Integer.parseInt(s);
		// int number = Integer.valueOf(s);
		Integer number = new Integer(s);

		// printing vlaues
		System.out.println("Number : " + number);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "hello world"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
	at java.base/java.lang.Integer.parseInt(Integer.java:658)
	at java.base/java.lang.Integer.<init>(Integer.java:1117)
	at com.javaprogramto.convert.string.toint.StringToIntException.main(StringToIntException.java:19)



7. Conclusion


In this article, We've seen how to convert string to integer in different ways in java with example programs.


Stream to Array - How To Convert Stream To Array In Java 8?

1. Overview

In this article, we'll explore the different ways to convert Stream to Array in Java 8.

I have shown in the previous article how to convert ArrayList<String> to String[] array in java 8.

Java 8 Stream api provides a method Stream.toArray() method which converts the string to array in a faster way.

Stream.of(String t) method is used to create Stream of Strings as Stream<String>. 

Learn How To Convert Stream To Array In Java 8?


We will be showing the conversion on the following in this article

1.1 Using Method Reference

1.2 Lambda Expression

1.3 Custom class stream to custom class array

1.4 On primitive types

But, for all the cases, you must use the Stream.toArray() method.

Stream.toArray() Syntax:

<A> A[] toArray(IntFunction<A[]> generator);

Let us explore each of these topics. In this article, We are going to show examples of how to convert Stream of String into a String array. But, you can convert any Stream of objects into any typed array.

Below all are possible with the toArray() method.

Example 1: Convert Stream<String> to String[] array

Example 2: Convert Stream<Employee> to Employee[] array

Example 3: Convert Stream<CustomClass> to CustomClass[] array

Example 4: Convert Stream<Integer> to Integer[] wrapper Integer array

Example 5: Convert Stream<Integer> to int[] primitive array


2. Using Method Reference

Method Reference is a broad topic. You can go through this article for an advanced level.

Method ref is indicated with "::" double colon operator introduced in java 8 and used to create an instance for a class.

Let us write a simple method with Method reference.

    public static String[]  convertStreamToArray(Stream<String> stringStream){
        String[] strArray = stringStream.toArray(String[]::new);
        return strArray;
    }
Next, write the code to test this method working fine or not.

Look at the complete program.
import java.util.Arrays;
import java.util.stream.Stream;

public class MethodRefStreamToArray {

    public static void main(String[] args) {

        Stream<String> stringStream = Stream.of("hello", "reader", "welcome", "to", "javaprogramto.com", "blog");

        String[] array1 = convertStreamToArray(stringStream);

        System.out.println("Array 1 : "+ Arrays.toString(array1));

        Stream<String> stringStream2 = Stream.of("seocond", "example", "stream to array");

        String[] array2 = convertStreamToArray(stringStream2);

        System.out.println("Array 2 : "+ Arrays.toString(array2));

    }

    public static String[] convertStreamToArray(Stream<String> stringStream) {

        String[] strArray = stringStream.toArray(String[]::new);

        return strArray;
    }
}
Output:
Array 1 : [hello, reader, welcome, to, javaprogramto.com, blog]
Array 2 : [seocond, example, stream to array]

3. Using Lambda Expression


Another way is to pass the lambda expression to the toArray() method. toArray() method takes IntFunction as an argument and it takes size as input and returns String[] array with size.
import java.util.Arrays;
import java.util.stream.Stream;

public class LambdaStreamToArray {

    public static void main(String[] args) {

        Stream<String> stringStream = Stream.of("hello", "reader", "welcome", "to", "javaprogramto.com", "blog");

        String[] array1 = convertStreamToArrayWithLambda(stringStream);

        System.out.println("Array 1 : "+ Arrays.toString(array1));

        Stream<String> stringStream2 = Stream.of("seocond", "example", "stream to array");

        String[] array2 = convertStreamToArrayWithLambda(stringStream2);

        System.out.println("Array 2 : "+ Arrays.toString(array2));

    }

    public static String[] convertStreamToArrayWithLambda(Stream<String> stringStream) {

        String[] strArray = stringStream.toArray(size -> {
            return new String[size];
        });

        return strArray;
    }
}
This program produces the output as same as the above section.

4. Using Custom Generator Class


toArray() method takes IntFunction as argument and it is a Functional Interface.

Let us create a custom class that implements the IntFunction and implements apply() method.
import java.util.Arrays;
import java.util.function.IntFunction;
import java.util.stream.Stream;

public class CustomIntFunctionStreamToArray {

    public static void main(String[] args) {

        Stream<String> stringStream = Stream.of("hello", "reader", "welcome", "to", "javaprogramto.com", "blog");

        String[] array1 = stringStream.toArray(new CustomIntFunction());

        System.out.println("Array 1 : "+ Arrays.toString(array1));

        Stream<String> stringStream2 = Stream.of("seocond", "example", "stream to array");

        String[] array2 = stringStream2.toArray(new CustomIntFunction());;

        System.out.println("Array 2 : "+ Arrays.toString(array2));

    }

}

class CustomIntFunction implements IntFunction<String[]>{

    @Override
    public String[] apply(int size) {
        return new String[size];
    }
}
Output:
Array 1 : [hello, reader, welcome, to, javaprogramto.com, blog]
Array 2 : [seocond, example, stream to array]

5. Stream to Primitive Or Wrapper Array conversion

Let us convert Stream of Integers into Integer Array.

Wrapper Stream to Wrapper[] Array Example

import java.util.Arrays;
import java.util.stream.Stream;

public class WrapperStreamToArray {

    public static void main(String[] args) {

        Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7);

        Integer[] array1 = integerStream.toArray(Integer[]::new);

        System.out.println("Integer Array 1 : " + Arrays.toString(array1));

        Stream<Integer> integerStream2 = Stream.of(11, 22, 33, 44, 55);

        Integer[] array2 = integerStream2.toArray(size -> new Integer[size]);

        System.out.println("Integer Array 2 : " + Arrays.toString(array2));

    }
}
Output:
Integer Array 1 : [1, 2, 3, 4, 5, 6, 7]
Integer Array 2 : [11, 22, 33, 44, 55]
If you pass the Integer array size as 0 as below will get the runtime exception.
Integer[] array2 = integerStream2.toArray(size -> new Integer[0]);
Exception:
Exception in thread "main" java.lang.IllegalStateException: Begin size 5 is not equal to fixed size 0
	at java.base/java.util.stream.Nodes$FixedNodeBuilder.begin(Nodes.java:1222)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:483)
	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:550)
	at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
	at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:517)
	at com.javaprogramto.java8.streams.toarray.WrapperStreamToArray.main(WrapperStreamToArray.java:18)

Wrapper Stream to int[] primitive Array Example

Stream api has another method mapToInt() method which returns the int primitive values as IntStream. Next, will need to call the toArray() method to get the int[] array.

Similar to this steam api has built-in support for mapToLong() and mapToDouble() methods. All of these methods come under Stream Intermediate Options which returns Stream output.
import java.util.Arrays;
import java.util.stream.Stream;

public class PrimitiveStreamToArray {

    public static void main(String[] args) {

        Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7);

        int[] array1 = integerStream.mapToInt(primitiveVlaue -> primitiveVlaue).toArray();

        System.out.println("int[] Array 1 : " + Arrays.toString(array1));

        Stream<Integer> integerStream2 = Stream.of(11, 22, 33, 44, 55);

        int[] array2 = integerStream2.mapToInt( i -> i).toArray();

        System.out.println("int[] Array 2 : " + Arrays.toString(array2));

    }
}

7. Exception

If the stream is already closed then it will throw runtime exception saying IllegarStateException and reason is "stream has already been operated upon or closed".
Array 1 : [hello, reader, welcome, to, javaprogramto.com, blog]Exception in thread "main" 
java.lang.IllegalStateException: stream has already been operated upon or closed
	at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:246)
	at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:517)
	at com.javaprogramto.java8.streams.toarray.CustomIntFunctionStreamToArray.main(CustomIntFunctionStreamToArray.java:19)

8. Conclusion


In this article, You've seen how to convert Any Stream to an Array in java 8 using toArray(), mapToInt(), and of() methods.

All Examples are shown are on GitHub.


Java 8 Stream Collect to List

1. Overview

In this tutorial, We'll learn how to convert the stream of items into the list.

Below are the examples to collect the stream to list using Collectors.collect() and Collectors.toCollection() method.


Java 8 Stream Collect to List

الثلاثاء، 23 نوفمبر 2021

Java - How to return empty array?

1. Overview

In this tutorial, we'll learn how to return an empty array in java in different ways.

An empty array means the array is not having any values and the length of the array is zero. Sometimes we need to return an empty array rather than returning null values.

Creating an empty array can be done in 3 ways.


All examples work for any type of array ex. int, double, custom type such as Emp, Student etc.

Java - How to return empty array?


Java Copy Array - 4 Ways to copy from one to another Array

1. Overview

In this tutorial, You'll learn how to copy the array from one to another without loosing any values.

If you are new to java programming, learn how to create an array in java in various ways? 

Copying an array can be done in multiple ways. Let us discuss all possible ways.

Read the article till end to see best option for your case.

2. Copy Array Using Another Reference


Let us first create an array with 5 values and assign to a variable originalArray.

In the next step, create a new reference variable named "copiedArray" and assign the originalArray to copiedArray.

Further, printing the two arrays on the console using "Arrays.toString()" method.
import java.util.Arrays;

public class CopyArrayRefAssignment {

	public static void main(String[] args) {
		// creating an array

		int[] originalArray = { 1, 2, 3, 4, 5 };

		// assigning to the original array to new ref.
		int[] copiedArray = originalArray;

		// printing the arrays
		System.out.println("Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

		// changing the values in the original array

		originalArray[0] = 100;
		originalArray[4] = 500;

		// printing both arrays after modification

		System.out.println("\nPrinting values after original array modifications");
		System.out.println("Modified Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

	}

}

Output:
Original Array : [1, 2, 3, 4, 5]
Copied Array : [1, 2, 3, 4, 5]

Printing values after original array modifications
Modified Original Array : [100, 2, 3, 4, 500]
Copied Array : [100, 2, 3, 4, 500]

From the above output, you could see that originalArray and copiedArray have the same values.

But, we changed the values of original array using its index. After that printed the original and copied arrays. 

You might have noticed that copiedArray values are changed as per the modified original array.

Hence, it is not advisable to use the array assignment if original array is going to be modified in future because two references points to same object in the heap memory area.

3. Copy Array Using Iteration


Second approach is to iterate the array using for loop and assign each value to new array.
public class CopyArrayRefIterateExample {

	public static void main(String[] args) {
		// creating an array

		int[] originalArray = { 1, 2, 3, 4, 5 };

		// assigning to the original array to new ref.
		int[] copiedArray = new int[originalArray.length];

		// iterating array and assigning to the new array

		for (int i = 0; i < originalArray.length; i++) {
			copiedArray[i] = originalArray[i];
		}

		// printing the arrays
		System.out.println("Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

		// changing the values in the original array

		originalArray[0] = 100;
		originalArray[4] = 500;

		// printing both arrays after modification

		System.out.println("\nPrinting values after original array modifications");
		System.out.println("Modified Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

	}

}
Output:
Original Array : [1, 2, 3, 4, 5]
Copied Array : [1, 2, 3, 4, 5]

Printing values after original array modifications
Modified Original Array : [100, 2, 3, 4, 500]
Copied Array : [1, 2, 3, 4, 5]

In this approach, we need to copy the each value to new array. You can observe the output is that any changes to the original array does not affect the copied array.

4. Copy Array Using Clone Approach


Next third approach, you'll see the example program using clone() method. You can understand the differences between deep copy vs shallow copy cloning in java.
public class CopyArrayCloneExample {

	public static void main(String[] args) {
		// creating an array

		int[] originalArray = { 1, 2, 3, 4, 5 };

		// cloning array using clone() method
		int[] copiedArray = originalArray.clone();
		

		// printing the arrays
		System.out.println("Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

		// changing the values in the original array

		originalArray[0] = 100;
		originalArray[4] = 500;

		// printing both arrays after modification

		System.out.println("\nPrinting values after original array modifications");
		System.out.println("Modified Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

	}

}
Output:
Original Array : [1, 2, 3, 4, 5]
Copied Array : [1, 2, 3, 4, 5]

Printing values after original array modifications
Modified Original Array : [100, 2, 3, 4, 500]
Copied Array : [1, 2, 3, 4, 5]

This approach works fine as similar to the above approach.

5. Copy Array Using System.arraycopy() Method


In the last approach, you'll use the System.arraycopy() method which does copy the values from original array for a given index range.
public class CopyArraySystemArraycopyExample {

	public static void main(String[] args) {
		// creating an array

		int[] originalArray = { 1, 2, 3, 4, 5 };

		// Creating a new array as same as original. 
		int[] copiedArray = new int[originalArray.length];

		// cloning array using clone() method
		System.arraycopy(originalArray, 0, copiedArray, 0, originalArray.length);

		// printing the arrays
		System.out.println("Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

		// changing the values in the original array

		originalArray[0] = 100;
		originalArray[4] = 500;

		// printing both arrays after modification

		System.out.println("\nPrinting values after original array modifications");
		System.out.println("Modified Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

	}

}
This approach also work well and could see it as used in many collections api internally.

Hence, this approach is better choice if you want to copy the large data set which is stored in array.

6. Conclusion


In this article, you've seen the various ways to copy array to another in java.

GitHub sample code


Java forEachRemaining() - Iterator foreach example in JDK 8

1. Overview

In this tutorial, we'll learn how to use Iterator forEachRemaining() method in java 8 efficiently when compared to the older java versions.

Iterator is an interface from collections api and is used to iterate over the collections objects.


Iterator methods:

The following methods are present in the Iterator interface till java 7.
boolean hasNext()
E next()
default void remove()
Java forEachRemaining() - Iterator foreach example

الاثنين، 22 نوفمبر 2021

Java Arrays - How to return array in java from method?

1, Overview


In this tutorial, We'll learn how to return an array from a method in java.

If you are new to java programming, please refer to the article on How to initialize an array in java?

Thump rules:

  • A method can return an array that is referencing another array.
  • The return type of method must be declared as the correct array type.
Java Return arrays - How to return array in java from method?

Java Get Current Timestamp

1. Overview

In this tutorial, We'll learn how to get the current timestamp in java in various ways.

Let us jump into the right examples with JDK 8 and older jdk.


Java Get Current Timestamp

Java Event Handler - Events and Listeners Examples

1. Overview

In this tutorial, We'll learn how to work with event handlers in java.

How to add events to the actions of users and work with the listeners in java.

When you are working on GUI based projects using AWT or Applets then you might have seen the scenarios where you need to change the state of an object from one form to another.

For example, add action when a button is pressed or when the text is entered then enable another text box.

Java Event Handler - Events and Listeners Examples

Building First Spring Boot REST API Application (Hello World Example)

1. Overview


In this tutorial, You'll learn how to create the first spring boot application in Spring Boot. This is like spring boot Hello world example. You will learn today how to create a spring boot rest API application from scratch step by step.

Building First Spring Boot REST API Application (Hello World Example)


Spring Boot is a subproject initiative done by the spring core development team. It manages internally many things for us automatically such as managing dependencies, spring traditional configurations, deploying in embed tomcat server and hosting as rest API.

Spring Boot 2.2.1
Java 1.8

Java HashMap with Example Programs + Java 8 Methods

1. Introduction


In this tutorial, We'll be learning HashMap API and its usage. HashMap is one of the implementations of the Map interface. HashMap is widely used in the realtime applications to store the key-value pair. This supports all kinds of operations needed on a daily basis to work on the dataset. This comes with most used built-in utility methods to add the values into map(), replace(), remove(), get() methods. We'll be showing java 8 new API changes to the HashMap such as compute(), replaceAll(), computeIfAbsent(), computeIfPresent(), merge() methods.

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable



Examples of HashMap In Java and Understand HashMap Real-Time usage



HashMap helps one object as an index to another object as the value. List index will be always a number whereas in Map it can be String, Integer, Float or Student or Trade objects.

Let us explore the most useful methods step by step.

Top 5 Spring Boot Ebooks - Developers Must Read in this year

Best Spring Boot Books

1. Introduction


In this article, We'll show the best books to read and learn Spring Boot from beginner to becoming an expert in this year.

In general, Many developers struggle to find the best books to learn any technology. Here, you will get the most useful to the beginner's step by the steep learning curve and with a clear explanation.

Spring Boot Tutorials

Top 5 Spring Boot Ebooks - Developers Must Read in 2020

الأحد، 21 نوفمبر 2021

[Fixed] org.apache.tomcat.util.bcel.classfile.classformatexception: invalid byte tag in constant pool: 19

1. ClassFormatException: Invalid byte tag in constant pool: 15 Overview


In this tutorial, We'll learn how to fix org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15. This is a common issue while working with Tomcat 7 or Tomcat 8 version. We'll provide you the various solutions to fix this error permanently.

Addition to this issue, you can find the other set of trouble shooting problems.

[Fixed] Java 8: Invalid byte tag in constant pool: 15 or 19 - Tomcat

Common issues on the same error. The solution is common in all cases.

Invalid byte tag in constant pool: 15
Invalid byte tag in constant pool: 16
Invalid byte tag in constant pool: 18
Invalid byte tag in constant pool: 19


[Fixed] Tomcat 7+ Java 8 : Invalid byte tag in constant pool: 15


Let me tell my store with this problem and how did the troubleshoot this issue.

org.apache.tomcat.util.bcel.classfile.classformatexception: invalid byte tag in constant pool: 19



I have started working with java version 1.7 and Apache Tomcat/7.0.12. After some time my mind was completely changed. Felt very curious really waiting to work with java 8 features.

Read the article on Java 8 Lambda Expressions Feature

Java 8 Predicate Examples - Conditions in JDK 8

1. Overview


In this tutorial, We'll learn how to work and use the Predicate Functional Interface.

In the previous post, We have discussed "Introduction to Functional Interfaces in Java 8". Explained an easy manner to understand the type of Functional Interfaces.

Predicate Functional interface is part of java.lang.function package.

Predicate is one of the categories of Function Interfaces (Suppliers, Consumer, Predicates and Function)

Java 8 Predicate All Methods Examples