Showing posts with label String Programs. Show all posts
Showing posts with label String Programs. Show all posts

Friday, January 7, 2022

Java Program To Find First Non-Repeated Character In String (5 ways)

1. Overview


In this article, We will be learning and understanding the various ways to find the first non repeated character in a given string in various ways along with Java 8 Streams. Many programs may face this type of question in programming interviews or face to face round.
Let us start with the simple approach and next discover the partial and single iteration through the string.

Java Program To Find First Non-Repeated Character In String (5 ways)


Saturday, November 20, 2021

Java - How to mix two strings and generate another?

1. Overview

In this tutorial, We'll learn how to mix and concatenate the two or more strings in java.

Strings are used to store the sequence of characters in the order in the memory and they are considered as objects.

Strings are located in java.lang package

If you are new to Strings, please go through the below string methods.



String creation can be done in two ways using new keyword and literals as below.
String s1 = new String("JavaProgramTo.com");
String s2 = "welcome, Java developer";
In the next sections, you will see examples of adding strings using different techniques.

Java - How to mix two strings and generate another?

Tuesday, November 16, 2021

Java add char - How to Add Character To String?

1. Overview

In this article, we'll learn how to add char to string in java. Char data type is used to store 1 character in java. Whereas String is used to store a set of characters stored one after another.

Now, we need to add the new char to the string at any position or at a specific position.

You can do this in 3 or more ways as you need.
But, The below methods are used to show the examples to append char to string.

Using the + operator for concat
Using StringBuilder
Using substring()
Java add char - How to Add Character To String?

Java - How to Convert Char To String?

1. Overview

In this tutorial, We'll learn how to convert char to string in java using Character.toString(), String.valueOf() and + operator with empty string.
Java - How to Convert Char To String?


2. Java Char to String Using Character.toString()


Character.toString(char) method takes the character as argument returns the same character as String format.

Character.toString() method returns a String with length or size exactly 1.

This method is available in java 1.4 onwards.

The below example is converting char to string java.
package com.javaprogramto.convert.chartostring;

/**
 * example to convert char to string in java using Character.toString() method.
 * 
 * @author javaprogramto.com
 *
 */
public class CharToStringExample1 {

	public static void main(String[] args) {

		// example 1

		char ch = 'c';

		String strC = Character.toString(ch);
		System.out.println("Example 1: ");
		System.out.println("Char in String : " + strC);
		System.out.println("returned string length : " + strC.length());

		// example 2

		char ch2 = 'z';

		String strZ = Character.toString(ch2);

		System.out.println("\nExample 2: ");
		System.out.println("Char in String : " + strZ);
		System.out.println("returned string length : " + strZ.length());

	}

}

Output:
Example 1: 
Char in String : c
returned string length : 1

Example 2: 
Char in String : z
returned string length : 1


3. Java Char to String Using String.valueOf(char)


String.valueOf() method takes the char as a parameter and returns a String with the char value.

valueOf() method always returns the string representation of char value and its length will be always 1.

Example:
package com.javaprogramto.convert.chartostring;

/**
 * example to convert char to string in java using String.valueOf() method.
 * 
 * @author javaprogramto.com
 *
 */
public class CharToStringExample2 {

	public static void main(String[] args) {

		// example 1
		char ch3 = 'x';

		String strC = String.valueOf(ch3);
		System.out.println("String.valueOf Example 1: ");
		System.out.println("Char in String : " + strC);
		System.out.println("returned string length : " + strC.length());

		// example 2
		char ch4 = '7';

		String strZ = String.valueOf(ch4);

		System.out.println("\nString.valueOf Example 2: ");
		System.out.println("Char in String : " + strZ);
		System.out.println("returned string length : " + strZ.length());

	}

}
Output:
String.valueOf Example 1: 
Char in String : x
returned string length : 1

String.valueOf Example 2: 
Char in String : 7
returned string length : 1

4. Java Char to String Using + operator with an empty string


You can use the + operator to add the char to the string which is empty.

+ operator can be used in the string concatenations.

First create the empty string literal "" and add the character to the string using + operator as below. This step will return the new string with only the character.
package com.javaprogramto.convert.chartostring;

/**
 * char to string using + operator
 * 
 * @author javaprogramto.com
 *
 */
public class CharToStringExample3 {

	public static void main(String[] args) {

		char ch3 = 'x';
		String returnedString = "" + ch3;
		System.out.println("Returned string 1 : " + returnedString);

		char ch1 = 'a';
		String returnedString2 = "" + ch1;
		System.out.println("Returned string 2 : " + returnedString2);

		char ch2 = 'b';
		String returnedString3 = "" + ch2;
		System.out.println("Returned string 3 : " + returnedString3);
	}
}

Output:
Returned string 1 : x
Returned string 2 : a
Returned string 3 : b

5. Conclusion


In this tutorial, We've seen converting char to string in java.





Monday, November 15, 2021

Java String to Long - How to Parse String Into Long?

1. Overview

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

This problem can be solved in many ways but we will look at the most commonly used in real-time applications.

Sometimes you get the number in string format. So, you need to parse the string to long value to perform the operations on the long number.


Let us look at each approach and understand its usage.
Java String to Long - How to Parse String Long?


2. Java Parse String to Long using Long.parseLong()


Long.parseLong() method takes the string object and parses the string into the long value.

This method works for positive and negative values.

The first character of the string is used for the sign of the number either plus(+) or minus(-) but this is optional.

Look at the below example program.
package com.javaprogramto.programs.strings.tolong;

public class StringToLongExample {

	public static void main(String[] args) {

		String positiveString = "12345";

		long longvalue1 = Long.parseLong(positiveString);
		System.out.println("Positive Long value 1 : " + longvalue1);

		String positiveString2 = "+12345";

		long longvalue2 = Long.parseLong(positiveString2);
		System.out.println("Positive Long value 2 : " + longvalue2);
		
		String negativeValue1 = "-12345";

		long longvalue3 = Long.parseLong(negativeValue1);
		System.out.println("Negative Long value 3 : " + longvalue3);

	}

}

Output:
Positive Long value 1 : 12345
Positive Long value 2 : 12345
Negative Long value 3 : -12345

3. Java Convert String to Long using Long.valueOf()


Long.valueOf() method is also from the Long class and it is a static method.

Long.valueOf() method takes the string value and converts it into the Long wrapper object. But whereas parseLong() method converts into primitive long value.

parseLong() method rules applies to valueOf() method.

Look at the below example.

package com.javaprogramto.programs.strings.tolong;

public class StringToLongExample {

	public static void main(String[] args) {

		String positiveString = "12345";

		long longvalue1 = Long.parseLong(positiveString);
		System.out.println("Positive Long value 1 : " + longvalue1);

		String positiveString2 = "+12345";

		long longvalue2 = Long.parseLong(positiveString2);
		System.out.println("Positive Long value 2 : " + longvalue2);
		
		String negativeValue1 = "-12345";

		long longvalue3 = Long.parseLong(negativeValue1);
		System.out.println("Negative Long value 3 : " + longvalue3);

	}

}

This program also produces the same output.


4. Java Convert String to Long using Long Constructor


Last way is using new Long(String) constructor.  But this way is deprecated.

package com.javaprogramto.programs.strings.tolong;

public class StringToLongExample3 {

	public static void main(String[] args) {

		String positiveString = "12345";

		Long longvalue1 = new Long(positiveString);
		System.out.println("Positive Long value 1 : " + longvalue1);

		String positiveString2 = "+12345";

		Long longvalue2 = new Long(positiveString2);
		System.out.println("Positive Long value 2 : " + longvalue2);
		
		String negativeValue1 = "-12345";

		Long longvalue3 = new Long(negativeValue1);
		System.out.println("Negative Long value 3 : " + longvalue3);

	}

}


5. Java String to Long - String is with non-digits


What happens if the string is having non-digits in it?

All of the above approaches will produce the runtime exception "NumberFormatException".

package com.javaprogramto.programs.strings.tolong;

public class StringToLongExample4 {

	public static void main(String[] args) {

		long one = Long.parseLong("abc133");
		
		Long two = Long.valueOf("abc133");
		
		Long three = new Long("abc133");
		
		
	}

}

The program fails at the runtime because string is having alphabets that are other than numbers.
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc133"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
	at java.base/java.lang.Long.parseLong(Long.java:707)
	at java.base/java.lang.Long.parseLong(Long.java:832)
	at com.javaprogramto.programs.strings.tolong.StringToLongExample4.main(StringToLongExample4.java:7)

6. Conclusion


In this article, we have seen how to parse String to Long in java and what are the possible error if the string is with non digits values.

But among all of these 3 ways, Long,parseLong() method is suggested to use because valueOf() and Long constructor uses internally parseLong() method. 





Friday, November 12, 2021

Java - Check If String is Subsequence of Other String

1. Overview

In this tutorial, we'll learn how to check whether the string is subsequence of another String in java.

This problem can be solved using iteration and recursive approach.

Java - Check If String is Subsequence of Other String


2 Whart is subsequence?


when zero or more characters are removed from in the input string then it is a valid subsequence. Here the the order is important.

if you understand this concept then you solve the problem easily. Remember suubsequcen go in the single direction, no backward direction.

Example String ABC
sub sequences are "", A, B, C, AB, AC, BC, ABC
"" is when all characters are removd
A, B, C are when two characters are removed.
AB, AC, BC when one character is removed
ABC when zero characters are removed.

CA, BA, CBA are not subsequences because these are not in the order of the string. CA -> after C there is no A in the input string, BA -> after B there is no A character input string.

Example 1:

String: "ABCDE"
Subsequence: "ACE"
Output: true

subsequence ACE is present in the string "ABCDE". ACE is present in the same order in the input string.

Example 2:

String: "ABCDE"
Subsequence: "AEC"
Output: false

AEC is not a subsequence because AE is a continuous sequence but C is not in the sequence in the input string. C is in between in the A and E in the input string.

3. Java - Check If String is Subsequence of Other String Using Iterative Approach


Observe the below alogirithm to solve this problem in O(n) time.

Input or other String: "ABCDE"
Subsequence: "ACE"

First take first characters from both strings and compare them. If two characters are equals then go for the next characters comparison from the both strings. If not then take the next character from the other string and compare it with the 1st character of the subsequence string.

Repeat this process until we reach the other string end. By end of this process, if all subsequences characters are matched then it is a valid subsequences.

if there are some characters left and not matched with the other string then it is not a valid subsequence.

Other String: ABCDE
subsequence: ACE

A) Take the first characters from both strings and compare them.
    A == A
    Both are same. Move the comparisons for the next characters.

B) Next, take second character from other string and subsequcne string.
    B == C
    No match. 

C) Now take the next character from the other string and compare with the C character from the subsequence current unmatched character.
    
    Next character from other string : C
    Curent unmatched character from subsequence string: C

    C == C
    Both are matched.

D) Now take the next character from both strings.

    Next character from other string : D
    Curent unmatched character from subsequence string: E

    D == E 
    No match

E) Now take the next character from the other string and compare with the E character from the subsequence current unmatched character.
    
    Next character from other string : E
    Curent unmatched character from subsequence string: E

    E == E

    Both are matched and no characters are left on the other string and there are no other characters.

And also there are no characters from the subsequence also. All characters are matched with other string.
So ACE is a valid subsequence of ABCDE.


If the subsequence is AEC then by end of comparisons of all characters from the other string with subsequcne, A character C is left from the subsequence string. Hence, AEC is not a valid subsequcne of ABCDE.

Look at the below code.
package com.javaprogramto.programs.strings;

public class StrintSubSequnceIterativeExample {

	public static void main(String[] args) {

		String otherString = "ABCDE";
		String subsequence = "ACE";

		boolean isValidSubsequence = checkSubsequence(otherString, subsequence);

		System.out.println(isValidSubsequence);

		otherString = "ABCDE";
		subsequence = "AEC";

		isValidSubsequence = checkSubsequence(otherString, subsequence);

		System.out.println(isValidSubsequence);

	}

	private static boolean checkSubsequence(String otherString, String subsequence) {

		// if the subsequence length is greather than subsequence, then inputs are not
		// valid and not subsequence.
		if (otherString.length() < subsequence.length()) {
			return false;
		}

		int subsequenceIndex = 0;
		for (int otherStringIndex = 0; otherStringIndex < otherString.length(); otherStringIndex++) {
			// whether there is a match or not with other string. we will increment other
			// string index by 1 always.

			if (otherString.charAt(otherStringIndex) == subsequence.charAt(subsequenceIndex)) {
				// if both characters are matching then incrementing the index of subsequence
				// string.
				subsequenceIndex++;
			}

		}

		// always subsequence length and sub sequence index should be same for a valid
		// sub sequence.
		return subsequence.length() == subsequenceIndex;
	}

}


Output:
true
false

In this program, we have passed two inputs with valid and invalid subsequences for the better understanding.

Time complexity: O(n)
Auxilary space complexity: O(1)

4. Java - Check If String is Subsequence of Other String Using Recursive Approach


Recursive approach is not suitable for this problem because iterative approach is best solution with no auxilary space.

If you use recustive way, then it uses the additional stacks recursive calls.

In the below code, we compare the character from the last index from both strings and go back to till the zero index.

And also we need to pass the current indexes to the recursive method.

Look at the below approach.
package com.javaprogramto.programs.strings.subsequence;

public class StrintSubSequnceRecursiveExample {

	public static void main(String[] args) {

		String otherString = "ABCDE";
		String subsequence = "ACE";

		boolean isValidSubsequence = checkSubsequence(otherString, subsequence, otherString.length(),
				subsequence.length());

		System.out.println(isValidSubsequence);

		otherString = "ABCDE";
		subsequence = "AEC";

		isValidSubsequence = checkSubsequence(otherString, subsequence, otherString.length(), subsequence.length());

		System.out.println(isValidSubsequence);

	}

	private static boolean checkSubsequence(String otherString, String subsequence, int otherLength, int subLength) {

		// if at any point if the sub sequence length becomes zero mean all character of
		// sub sequence are matched
		// or if other is reached 0 index and sub sequences also reached 0 index at the
		// same time then it is a valid sub sequence. so because of this we are first
		// checking the sub sequence length 0
		if (subLength == 0) {
			return true;
		}

		if (otherLength == 0) {
			return false;
		}

		// comparing the last characters first and then going backward for the previous
		// letters comparison.
		if (otherString.charAt(otherLength - 1) == subsequence.charAt(subLength - 1)) {
			// if matched then decrement the legth for the both strings.
			return checkSubsequence(otherString, subsequence, otherLength - 1, subLength - 1);
		} else {
			// if no match then decrement only for the other string. because sub sequence
			// current character is not matched yet
			return checkSubsequence(otherString, subsequence, otherLength - 1, subLength);
		}
	}

}

This program also produces the same output.

Time complexity: O(n)
Auxilary space complexity: O(n)

5. Conclusion


In this article, we have seen how to check string is sub sequence of another string in java using iterative and recursive approaches.



Java - Checking Whether Two Strings are Anagrams

1. Overview

In this tutorial, We'll learn how to check if the two given strings are anagrams or not in java programming language.

Anagram means two string should be same characters but order is not important. So, that means characters can be another order.

Note that character count also should be matched. Suppose if the string1 has 10 chars where as string 2 has 9 characters so these two are not anagams.

Java - Checking Whether Two Strings are Anagrams


Example 1:

String 1: "abaac"

String 2: "caaba"

Output: true

Example 2:

String 1: "listen"

String 2: "silent"

Output: true

Example 3:

String 1: "aap"

String 2: "pap"

Output: false

2. Java - Checking Whether Two Strings are Anagrams Using Sort

First solution is sort the first two string characters and then compare them. If both strings are same then these two strings are anagrams. If the two strings are not same then strings are not anagrams.

Use Arrays.sort() method to sort the string character as char array.

Use String.equals() method to compare the two strings contents.

Look at the below code.

Time complexicity: O(nlogn)

package com.javaprogramto.programs.strings.anagrams;

import java.util.Arrays;

public class CheckStringsAnagramsExample {

	public static void main(String[] args) {

		String str1 = "abaac";
		String str2 = "caaba";

		boolean isAnagram = isStrinsAnagrams(str1, str2);
		System.out.println(isAnagram);

		str1 = "listen";

		str2 = "silent";

		isAnagram = isStrinsAnagrams(str1, str2);
		System.out.println(isAnagram);

		str1 = "aap";

		str2 = "pap";

		isAnagram = isStrinsAnagrams(str1, str2);
		System.out.println(isAnagram);

	}

	private static boolean isStrinsAnagrams(String str1, String str2) {

		// converting str1 to char array
		char[] strCharArray1 = str1.toCharArray();

		// converting str2 to char array
		char[] strCharArray2 = str2.toCharArray();

		// sorting two strings char arrays using Arrays.sort() method
		Arrays.sort(strCharArray1);
		Arrays.sort(strCharArray2);

		// converting char arrays back to strings
		str1 = new String(strCharArray1);
		str2 = new String(strCharArray2);

		// comparing two strings
		if (str1.equals(str2))
			return true;

		return false;
	}

}

Output:

true
true
false

3. Java - Checking Whether Two Strings are Anagrams - Optimized Solution

The above solution takes nlogn logarthemetic execution time. This may not work for the larger input data.

We need to always think before using sorting logic on any problem.

To avoid sorting, we need to think different for better approach.

Here is problem is we need to check each and every character of string 1 is present in the string 2.

Actually, for this problem sorting is not an efficient answer.

We will take one integer array with size of 256. This value is the typical characters are stored in 8 bits so there will be only 256 possible characters.

By default, all values in the int array are initialized with 0.

First, Take the each character from the string and go to the corresponding location in the int array increaemtn by 1 and repeat the same process.

Next, take the each character from second string and go the corresponding location in the same int array, decrement the value 1.

If the one character is present in both strings then first count is increment by 1 and decreemnted by 1. So, count value in the int array becomes 0.

If the one character is present in the first array and the same character element is not present in the second string then the value in the count array will non zero value.

After traversing the two strings, we will check the counts int array values, if any index value is non zero then two strings are not anagrams. 

If all values in the count array is zero then inputs are anagrams.

Look at the below code.

package com.javaprogramto.programs.strings.anagrams;

public class CheckStringsAnagramsExample2 {

	public static void main(String[] args) {

		String str1 = "abaac";
		String str2 = "caaba";

		boolean isAnagram = isStrinsAnagramsOptimized(str1, str2);
		System.out.println(isAnagram);

		str1 = "listen";

		str2 = "silent";

		isAnagram = isStrinsAnagramsOptimized(str1, str2);
		System.out.println(isAnagram);

		str1 = "aap";

		str2 = "pap";

		isAnagram = isStrinsAnagramsOptimized(str1, str2);
		System.out.println(isAnagram);

	}

	private static boolean isStrinsAnagramsOptimized(String str1, String str2) {

		// if two strings lengths are not same then return false
		if (str1.length() != str2.length()) {
			return false;
		}
		int arraySize = 256;

		int[] countsArray = new int[arraySize];

		// increment by 1 from str1, decrement by 1 from str2
		for (int i = 0; i < str1.length(); i++) {
			countsArray[str1.charAt(i)]++;
			countsArray[str2.charAt(i)]--;
		}

		// checking any value is non zero in the counts arrray.
		for (int i = 0; i < countsArray.length; i++) {
			if (countsArray[i] != 0) {
				return false;
			}
		}

		return true;
	}
}


Output:

true
true
false

This code also generates the same output with O(n).

Time complexity: O(n)

Space complexity: O(256)

4. Conclusion

In this tutorial, We've seen how to check if the two strings are Anagrams or not in java.

GitHub

How to sort an array in Java 8 - Arrays.sort()?

How to count substring occurrences in String in Java?

Thursday, November 11, 2021

Java - Counting Substring Occurrences In A String

1. Overview

In this tutorial, We'll learn how to find the count of substring present in the input string in java.

Examples:

String: 222, substring = 22
Output: 2

String: madam, substring = ma
Output: 1

String: 1234, substring = 43
Output: 0
Java - Counting Substring Occurrences In A String


2. Java - Counting Substring Occurrences In A String using indexOf()


The below code is implemented based on the String class indexOf() method.
package com.javaprogramto.programs.strings.substring.count;

public class SubstringCountExample {

	public static void main(String[] args) {

		int count = countSubStringInString("222", "22");
		System.out.println(count);

		count = countSubStringInString("madam", "ma");
		System.out.println(count);

	}

	public static int countSubStringInString(String string, String toFind) {
		int position = 0;
		int count = 0;
		while ((position = string.indexOf(toFind, position)) != -1) {
			position = position + 1;
			count++;
		}
		return count;
	}

}

Output:
2
1

3. Java - Counting Substring Occurrences In A String using Pattern and Match

package com.javaprogramto.programs.strings.substring.count;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SubstringCountExample2 {

	public static void main(String[] args) {

		int count = countSubStringInString("222", "22");
		System.out.println(count);

		count = countSubStringInString("madam", "ma");
		System.out.println(count);

	}

	public static int countSubStringInString(String string, String toFind) {
		Pattern pattern = Pattern.compile(Pattern.quote(toFind));
		Matcher matcher = pattern.matcher(string);
		int position = 0;
		int count = 0;
		while (matcher.find(position)) {
			position = matcher.start() + 1;
			count++;
		}
		return count;
	}
}

This code also produces the same output as in above section.


4. Java - Counting Substring Occurrences In A String Using While Loop and charAt()

package com.javaprogramto.programs.strings.substring.count;

public class SubstringCountExample3 {

	public static void main(String[] args) {

		int count = countSubStringInString("22222", "22");
		System.out.println(count);

		count = countSubStringInString("madam", "ma");
		System.out.println(count);

	}

	public static int countSubStringInString(String string, String toFind) {
		int M = toFind.length();
		int N = string.length();
		int res = 0;

		for (int i = 0; i <= N - M; i++) {

			int j;
			for (j = 0; j < M; j++) {
				if (string.charAt(i + j) != toFind.charAt(j)) {
					break;
				}
			}

			if (j == M) {
				res++;
				j = 0;
			}
		}
		return res;
	}
}

Time complexity : O( M * N)

5. Conclusion


In this article, we've seen how to find the frequency of substring in the input string in java.



Java Program - Check If String Contains A Substring

1. Overview

In this tutorial, We'll learn how to find and check if the string contains the substring in java.

This problem is commonly asked in the interview rounds. 

There are many solutions are present for this problem using java string api methods and third party api's also.

Let us write the quick program to understand the all methods.

Java Program - Check If String Contains A Substring

2. Java - Check If String Contains A Substring Using String.contains()

String class is added with contains() method which takes another method. contains() method returns true, if the passed string is present inside the current string, otherwise returns false.

Look at the below code.

package com.javaprogramto.programs.strings.substrin;

public class StringContainsSubstringExample {

	public static void main(String[] args) {

		String input = "hello world - welcome";
		String substring = "world";
		boolean isSubstring = input.contains(substring);

		System.out.println(isSubstring);

		substring = "llo";
		isSubstring = input.contains(substring);

		System.out.println(isSubstring);

		substring = "java";
		isSubstring = input.contains(substring);

		System.out.println(isSubstring);

	}
}

Output:

true
true
false

First two substring are present in the input string. So contains() method returned true. The 3rd string "java" is not present in the input string. So, contains() method returned false.

And also note that contains() method is case sensitive.

If you pass substring as "Hello" which does not match the "hello" from the input string because h is lower in the input and upper in the sub string.

Refer the below code.

substring = "Hello";
isSubstring = input.contains(substring);

System.out.println(isSubstring);

Output:

false


3. Java - Check If String Contains A Substring Using String.indexOf() or lastIndexOf()

Next solution is using the String class indexOf() or lastIndexOf() methods.

if the match is found then these method returns the starting of the index of substring from input string, otherwise -1 if no match found.

Example:

package com.javaprogramto.programs.strings.substrin;

public class StringContainsSubstringExample2 {

	public static void main(String[] args) {

		String input = "hello world - welcome";
		String substring = "world";
		int index = input.indexOf(substring);

		System.out.println(index);

		substring = "llo";
		index = input.lastIndexOf(substring);

		System.out.println(index);

		substring = "java";
		index = input.indexOf(substring);

		System.out.println(index);

		substring = "Hello";
		index = input.lastIndexOf(substring);

		System.out.println(index);

	}
}

Output:

6
2
-1
-1


indexOf() and lastIndexOf() methods also case sensitive.

4. Java - Check If String Contains A Substring Using Regular Expression

Next solution to solve this problem is with help of regular expression. We need to use the Pattern.quote() method and this method takes the regex pattern. 

This method takes care if the substring has the special characters then escaping them is taken care by quote method.

Look at the following code.

package com.javaprogramto.programs.strings.substrin;

import java.util.regex.Pattern;

public class StringContainsSubstringExample3 {

	public static void main(String[] args) {

		String input = "hello world - welcome";
		String substring = "world";
		boolean isPatternMatched = input.matches("(?i).*" + Pattern.quote(substring) + ".*");

		System.out.println(isPatternMatched);

		substring = "llo";
		isPatternMatched = input.matches("(?i).*" + Pattern.quote(substring) + ".*");

		System.out.println(isPatternMatched);

		substring = "java";
		isPatternMatched = input.matches("(?i).*" + Pattern.quote(substring) + ".*");

		System.out.println(isPatternMatched);

	}
}


Output:

true
true
false

5. Java - Check If String Contains A Substring Using Apache Commons

Apache commons lang third party api also provided a utility method to handle this problem.

contains(): Checks the given substring is present in the main string.

containsIgnoreCase(): Same as above but ignores the case sensitive

indexOf(): Returns the index of substring if present, else returns -1.


package com.javaprogramto.programs.strings.substrin;

import org.apache.commons.lang3.StringUtils;

public class StringContainsSubstringExample4 {

	public static void main(String[] args) {

		// StringUtils.contains() example
		String input = "hello world - welcome";
		String substring = "world";
		boolean isPatternMatched = StringUtils.contains(input, substring);

		System.out.println(isPatternMatched);

		// StringUtils.containsIgnoreCase() example
		substring = "Hello";
		isPatternMatched = StringUtils.containsIgnoreCase(input, substring);

		System.out.println(isPatternMatched);

		// StringUtils.isIndexFound() example
		substring = "welco";
		int isIndexFound = StringUtils.indexOf(input, substring);

		System.out.println(isIndexFound);

	}
}

Output:

true
true
14

6. Conclusion

In this article, We've seen the various ways to check whether the string contains the substring in it or not in java.

Apache commons StringUtils class has many utility methods. These are the additional methods which is not shown in the above example indexOfAny(), indexOfAnyBut(), indexOfDifference(). All of these methods can be used to solve the problem statement.

GitHub

StringUtils

String examples

Pattern.quote() 

Wednesday, November 10, 2021

Java 8 - Sorting An Array Of Strings By Length

1. Overview

In this tutorial, We'll learn how to sort an array of string by length in java 8.
Java 8 - Sorting An Array Of Strings By Length


2. Java 8 - Sorting An Array Of Strings By Length Using Arrays.sort()


First solution is using Arrays.sort() and Integer.compare() methods.
package com.javaprogramto.programs.strings.sort.length;

import java.util.Arrays;

public class SortStringsByLengthExample {

	public static void main(String[] args) {

		String[] words = { "hello", "how", "are", "u", "doing" };
		System.out.println("string array before sorting : "+Arrays.toString(words));
		
		
		sortArrayByLength(words, Sort.ASC);
		
		System.out.println("string array after sorting : "+Arrays.toString(words));

	}

	public static void sortArrayByLength(String[] strs, Sort direction) {
		if (direction.equals(Sort.ASC)) {
			Arrays.sort(strs, (String s1, String s2) -> Integer.compare(s1.length(), s2.length()));
		} else {
			Arrays.sort(strs, (String s1, String s2) -> (-1) * Integer.compare(s1.length(), s2.length()));
		}
	}

	public enum Sort {
		ASC, DESC
	}
}

Output:
string array before sorting : [hello, how, are, u, doing]
string array after sorting : [u, how, are, hello, doing]

3. Java 8 - Sorting An Array Of Strings By Length Using Comparator.comparingInt()


Next solution is based on the Comparator.comparingInt() method. In java 8, Comparator interface is enriched with the comparingInt() and this takes a int returned function. This int is the key for sorting.

And reversed() method also added to the Comparator interface. This function reverses the current comparator.
package com.javaprogramto.programs.strings.sort.length;

import java.util.Arrays;
import java.util.Comparator;

public class SortStringsByLengthExample2 {

	public static void main(String[] args) {

		String[] words = { "hello", "how", "are", "u", "doing" };
		System.out.println("string array before sorting : " + Arrays.toString(words));

		sortArrayByLengthUsingComparator(words, Sort.DESC);

		System.out.println("string array after sorting : " + Arrays.toString(words));

	}

	public static void sortArrayByLengthUsingComparator(String[] strs, Sort direction) {
		if (direction.equals(Sort.ASC)) {
			Arrays.sort(strs, Comparator.comparingInt(String::length));
		} else {
			Arrays.sort(strs, Comparator.comparingInt(String::length).reversed());
		}
	}

	public enum Sort {
		ASC, DESC
	}
}

Output:
string array before sorting : [hello, how, are, u, doing]
string array after sorting : [hello, doing, how, are, u]


4. Java 8 - Sorting An Array Of Strings By Length By Collecting Result using sorted() and toArray() methods


In the above solutions the result is not collected into the new array and the method type is void.
And also here the original array is sorted.

Now, in this solution the original array remain untouched with help of sorted() and toArray() methods.

Look at the below code.
package com.javaprogramto.programs.strings.sort.length;

import java.util.Arrays;
import java.util.Comparator;

public class SortStringsByLengthExample3 {

	public static void main(String[] args) {

		String[] words = { "hello", "how", "are", "u", "doing" };
		System.out.println("string array before sorting : " + Arrays.toString(words));

		String[] sortedArrayByLength = sortArrayByLengthUsingSorted(words, Sort.DESC);

		System.out.println("original array after sorting : " + Arrays.toString(words));
		System.out.println("new string array after sorting : " + Arrays.toString(sortedArrayByLength));

	}

	public static String[] sortArrayByLengthUsingSorted(String[] strs, Sort direction) {
		if (direction.equals(Sort.ASC)) {
			return Arrays.stream(strs)
					.sorted(Comparator.comparingInt(String::length))
					.toArray(String[]::new);
		} else {
			return Arrays.stream(strs)
					.sorted(Comparator.comparingInt(String::length)
					.reversed())
					.toArray(String[]::new);
		}
	}

	public enum Sort {
		ASC, DESC
	}
}

Output:
string array before sorting : [hello, how, are, u, doing]
original array after sorting : [hello, how, are, u, doing]
new string array after sorting : [hello, doing, how, are, u]


5. Conclusion


In this article, we've seen the different solutions to sort an array of string by length in java 8.



Java 8 - Find Most Repeated Character In String

1. Overview

In this tutorial, We'll learn how to find the character most appeared in the string in java.


Finding most frequently occurring character from string can be solved in many ways. But, we will present the most used and efficient solutions.

At the end, how to solve this problem using java 8 stream api methods.

Java 8 - Find Most Repeated Character In String


2. Java - Find Most Repeated Character In String Using HashMap


First, Let us solve this problem using collection api HashMap class.

In this approach, Create the HashMap instance using new keyword.

Convert the string to char array using to toCharArray(). Then iterate the char array over the for loop. Take each character and add it to the HashMap with the value as current number of instances. 
If the character is already present in the HashMap then increment the existing value by 1 and update the the HashMap.

Like this, perform the steps till last character of the string. By end, hash map contains the character which is most repeated.

Next, get the max of values of HashMap using Collections.max() method.

Now, get the character from HashMap which value is matching to the max value from above step.

Look at the below code.
package com.javaprogramto.programs.strings.find.most;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.tuple.Pair;

public class FindMostRepeatedCharacterInStringExample {

	public static void main(String[] args) {

		String input = "hello world";

		Pair<Character, Integer> maxCharCountPair = getMostRepeatedCharacterFromString(input);

		System.out.println("Input string : " + input);
		System.out.println(maxCharCountPair.getKey() + " is the most repeated character for "
				+ maxCharCountPair.getValue() + " times.");

	}

	private static Pair<Character, Integer> getMostRepeatedCharacterFromString(String input) {

		Map<Character, Integer> countMap = new HashMap<>();

		char[] chars = input.toCharArray();

		// storing the char and its count in the hashmap
		for (char ch : chars) {

			if (!Character.isWhitespace(ch)) {

				Integer currentCount = countMap.get(ch);

				if (currentCount == null) {
					countMap.put(ch, 1);
				} else {
					countMap.put(ch, ++currentCount);
				}

			}
		}

		// getting the max count from counter map.
		Integer maxCharacterCount = Collections.max(countMap.values());

		char maxCharacter = Character.MIN_VALUE;

		// getting the max occurred character.
		for (Entry<Character, Integer> entry : countMap.entrySet()) {
			if (entry.getValue() == maxCharacterCount) {
				maxCharacter = entry.getKey();
			}
		}

		return Pair.of(maxCharacter, maxCharacterCount);
	}

}

Output:
Input string : hello world
l is the most repeated character for 3 times.

The above program compiles and run without any errors.  But this is lengthy program using HashMap.

Here, we have captured the most repeated character and its count in Pair object. Most repeated char and its value is retrieved from getKey() and getValue() from Pair instance.


3. Java - Find Most Repeated Character In String Using ASCII sized Array


You might have observed that there are many loops and getting the max from HashMap and its traversals. Because of many operations, the execution may take longer for the larger inputs.

Now, we'll see another efficient approach using ASCII codes.

First, we will initialize the new empty int array with size of 256 which is the no of ASCII codes.
The same concept is used in solving the problem to find the first non repeated character from string.

look at the below program.
package com.javaprogramto.programs.strings.find.most;

import org.apache.commons.lang3.tuple.Pair;

public class FindMostRepeatedCharacterInStringExample2 {

	public static void main(String[] args) {

		String input = "hello world";

		Pair<Character, Integer> maxCharCountPair = getMostRepeatedCharacterFromString(input);

		System.out.println("Input string : " + input);
		System.out.println(maxCharCountPair.getKey() + " is the most repeated character for "
				+ maxCharCountPair.getValue() + " times.");

	}

	private static Pair<Character, Integer> getMostRepeatedCharacterFromString(String input) {

		int[] asciiIntArray = new int[256];

		char[] chars = input.toCharArray();

		int mostAppearanceCount = 0;
		char mostAppearedChar = Character.MIN_VALUE;

		// storing the char and its count in the hashmap
		for (char ch : chars) {

			if (!Character.isWhitespace(ch)) {

				int asciiCode = (int) ch;

				asciiIntArray[asciiCode]++;

				if (asciiIntArray[asciiCode] > mostAppearanceCount) {
					mostAppearanceCount = asciiIntArray[asciiCode];
					mostAppearedChar = ch;

				}

			}
		}

		return Pair.of(mostAppearedChar, mostAppearanceCount);
	}

}

This program also produces the same output and this is an optimized logic. Works extremely well for large sized inputs.


4. Java 8 Solution To Find Most Repeated Character In String


The last solution, we will learn using java 8 functional style programming.

Using java 8, this problem can be solved in the single line but for the understanding purpose, we are putting into multiple lines.

Look at the below java 8 sample code.
package com.javaprogramto.programs.strings.find.most;

import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.tuple.Pair;

public class FindMostRepeatedCharacterInStringExample3 {

	public static void main(String[] args) {

		String input = "hello world";

		Pair<Character, Long> maxCharCountPair = getMostRepeatedCharacterFromString(input);

		System.out.println("Input string : " + input);
		System.out.println(maxCharCountPair.getKey() + " is the most repeated character for "
				+ maxCharCountPair.getValue() + " times.");

	}

	private static Pair<Character, Long> getMostRepeatedCharacterFromString(String input) {
		
		return input.chars()
				.filter(c -> Character.isWhitespace(c) == false) // ignoring space
				.mapToObj(c -> (char) c)
				.collect(Collectors.groupingBy(c -> c, Collectors.counting()))
				.entrySet()
				.stream()
				.max(Map.Entry.comparingByValue())
				.map(p -> Pair.of(p.getKey(), p.getValue()))
				.orElse(Pair.of(Character.MIN_VALUE, -1L));
	}

}


This program also generates the same output.

5. Conclusion


In this article, we've seen how to find the most appeared character from string in java in different ways.



Tuesday, November 9, 2021

Java 8 Streams - Removing A Character From String

1. Overview

In this tutorial, We'll learn how to remove the specific character from the given string in java with java 8 streams api.

This problem can be solved in many ways but we will solve in most used 4 ways.
Java 8 Streams - Removing A Character From String


2. Removing A Character From String Using replaceAll()


First, we use the replaceAll() method from String class. This method takes the regex and string to be replaced with the regex matched substring.

Look at the following example.
package com.javaprogramto.programs.strings.remove.character;

public class StringRemoveCharacterExample {

	public static void main(String[] args) {

		String input = "hello 0world 00";

		String output = input.replaceAll("0", "");
		
		System.out.println("Input string 1 : "+input);
		System.out.println("Output string after removing the + symbol : "+output);
	}
}

Output:
Input string 1 : hello 0world 00
Output string after removing the + symbol : hello world 
The above code does not work for the special characters. If input string contains any one of these characters(<, (, [, {, \, ^, -, =, $, !, |, ], }, ), ?, *, +, ., >) then it will throw PatternSyntaxException.
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+
^
	at java.base/java.util.regex.Pattern.error(Pattern.java:2029)
	at java.base/java.util.regex.Pattern.sequence(Pattern.java:2204)
	at java.base/java.util.regex.Pattern.expr(Pattern.java:2070)
	at java.base/java.util.regex.Pattern.compile(Pattern.java:1784)
	at java.base/java.util.regex.Pattern.<init>(Pattern.java:1431)
	at java.base/java.util.regex.Pattern.compile(Pattern.java:1070)
	at java.base/java.lang.String.replaceAll(String.java:2141)
	at com.javaprogramto.programs.strings.remove.character.StringRemoveCharacterExample.main(StringRemoveCharacterExample.java:9)

To handle the special escape characters, we need to pass the regex pattern to Pattern.quote() method. This method converts into the literal pattern matching string.
package com.javaprogramto.programs.strings.remove.character;

import java.util.regex.Pattern;

public class StringRemoveCharacterExample2 {

	public static void main(String[] args) {

		String input = "hello +world ++";

		String output = input.replaceAll(Pattern.quote("+"), "");
		
		System.out.println("Input string 1 : "+input);
		System.out.println("Output string after removing the + symbol : "+output);
	}
}


Output:
Input string 1 : hello +world ++
Output string after removing the + symbol : hello world 

3. Removing A Character From String Using StringBuilder


Next, let us look at the another approach to solve this problem using StringBuilder.

Here, we need to iterate the string character over the for loop and compare each of them with the character to remove. If the current character is not matched to the removal character then add the current char to the StringBuilder using append() method.


The example code is below.
package com.javaprogramto.programs.strings.remove.character;

public class StringRemoveCharacterExample3 {

	public static void main(String[] args) {

		String input = "hello +world ++";
		char removalCh = '+';

		char[] chars = input.toCharArray();

		StringBuilder builder = new StringBuilder();

		for (char ch : chars) {

			if (ch != removalCh) {
				builder.append(ch);
			}

		}

		System.out.println("Input string 1 : " + input);
		System.out.println("Output string after removing the + symbol : " + builder.toString());
	}
}
Output:
Input string 1 : hello +world ++
Output string after removing the + symbol : hello world 

This program works for all escape characters also without any runtime exceptions.

4. Java 8 Streams - Removing A Character From String


Next solution is in java 8 using stream api methods.

Java 8 example:
package com.javaprogramto.programs.strings.remove.character;

import java.util.stream.Collectors;

public class StringRemoveCharacterExample4 {

	public static void main(String[] args) {

		String input = "hello +world ++";
		char removalCh = '+';

		String output = input.chars()
							.filter(ch -> ch != removalCh)
							.mapToObj(ch -> String.valueOf(ch))
							.collect(Collectors.joining());

		System.out.println("Input string 1 : " + input);
		System.out.println("Output string after removing the + symbol : " + output);
	}
}

If you want to remove the surrogate pairs then use codepoints() instead of chars() method and compare the codepoints rather than character.

5. Java Removing A Character From String Using Apache Commons


As of now, all examples shown are based on the java api but apache commons lang api has builtin utility class StringUtils.

Use StringUtils.remove() method to remove the given character from the string.

Example:
package com.javaprogramto.programs.strings.remove.character;

import org.apache.commons.lang3.StringUtils;

public class StringRemoveCharacterExample5 {

	public static void main(String[] args) {

		String input = "hello +world ++";
		char removalCh = '+';

		String output = StringUtils.remove(input, removalCh);

		System.out.println("Input string 1 : " + input);
		System.out.println("Output string after removing the + symbol : " + output);
	}
}

6. Conclusion


In this article, we've seen how to delete or remove the character from the string in java 8 and using third party api's.


Java 8 - Remove Duplicate Characters From String

1. Overview

In this tutorial, We'll learn how to remove all duplicate characters from the string in java and new java 8 stream api.

This problem can be solved in many ways but we focus on 3 important solutions.

Java 8 - Remove Duplicate Characters From String



2. Java Remove Duplicate Characters From String - StringBuilder


We use the StringBuilder to solve this problem. First, take the each character from the original string and add it to the string builder using append() method. Further, when adding the next character than use indexOf() method on the string builder to check if this char is already present in the string builder. If it is already present then we will not add it again to the string builder.

The same process is repeated for all the chars of original string. At final, string builder will have only the uniques values.

Look at the below code.
package com.javaprogramto.programs.strings.remove.duplicates;

public class StringRemoveDuplicatesExample1 {

	public static void main(String[] args) {

		String orignalString = "world world";

		StringBuilder builder = new StringBuilder();

		for (int i = 0; i < orignalString.length(); i++) {

			if (builder.indexOf(String.valueOf(orignalString.charAt(i))) == -1) {

				builder.append(orignalString.charAt(i));

			}
		}

		System.out.println("Original String : " + orignalString);
		System.out.println("After removing the duplicates : " + builder.toString());

	}

}

Output:
Original String : world world
After removing the duplicates : world 

From the output, you can observe that input has world word twice but the output is world once. So, duplicate chars are deleted. This code will work for any kind of input strings.

In the above program we used charAt() method, instead you can use toCharArray() method also to run the for loop.


3. Java Remove Duplicate Characters From String - HashSet


Next, we use the collection api HashSet class and each char is added to it using HashSet add() method.
add() method returns false if the char is ready present in the HashSet.

The same process is repeated till the last char of the string. So, at the end StringBuilder contains only distinct values.

Look at the below example code.
package com.javaprogramto.programs.strings.remove.duplicates;

import java.util.HashSet;
import java.util.Set;

public class StringRemoveDuplicatesExample2 {

	public static void main(String[] args) {

		String orignalString = "world world";

		StringBuilder builder = new StringBuilder();
		Set<Character> set = new HashSet<>();

		char[] chars = orignalString.toCharArray();

		for (char ch : chars) {

			if (set.add(ch)) {
				builder.append(ch);
			}
		}
		System.out.println("Original String : " + orignalString);
		System.out.println("After removing the duplicates : " + builder.toString());

	}

}

Output is same as above section.

4. Java 8 Streams - Remove Duplicate Characters From String


Finally, apply the java 8 functional style to eliminate the duplicates from the string.

Below is the sample code using java 8 streams.
package com.javaprogramto.programs.strings.remove.duplicates;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

public class StringRemoveDuplicatesExample3 {

	public static void main(String[] args) {

		String orignalString = "world world";

		String output = Arrays.asList(orignalString.split(""))
								.stream()
								.distinct()
								.collect(Collectors.joining());

		System.out.println("Original String : " + orignalString);
		System.out.println("After removing the duplicates : " + output);

	}

}


In this solution part, first converted the string into a list using split("") method which does split each character as a single character string.

stream() method converts List<String> into Stream<String>.

Next, distinct() method deletes all duplicates strings from it. Here, distinct() method is a intermediate operation as result Stream<String> is returned.
Finally, collect() terminal operation that collects all string into a one string with the help of Collectors.joining() method.

5. Conclusion


In this article, We've seen how to delete all duplicates from the String using older jdk and new java 8 api.



Java 8 Streams - Checking Whether String is Palindrome Or Not

1. Overview

In this tutorial, We'll learn how to check the given string is palindrome or not in java 8 programming.

Palindrome means when the string is reversed, it is as same as the original string.

Example: Input string is abcba and when it is revered abcba. Here both are same so this string is called as palindrome.

Java 8 Streams - Checking Whether String is Palindrome Or Not


2. Java Check String Palindrome - Two Pointers


This is a simple solution without using java 8 concepts. Here we take two pointer right and left. 
right value is initialed with 0 and left is with string length -1.

We take these two indexes values from string using charAt(index) method and compares them inside a while loop. If these two are not same then the given string is not a palindrome.

If equals, then increment right by 1 and decrement left by 1.
Repeat the comparisons steps until the right >= left or for any unmatch.

Look at the below example.
package com.javaprogramto.programs.strings.palindrome;

public class StringCheckPalindrome1 {

	public static void main(String[] args) {

		String input1 = "hello";
		boolean isPalindrome = isPalindrome(input1);
		System.out.println("Is " + input1 + " palindrome? " + isPalindrome);

		String input2 = "abcba";
		isPalindrome = isPalindrome(input2);
		System.out.println("Is " + input2 + " palindrome? " + isPalindrome);
	}

	private static boolean isPalindrome(String input) {

		int right = 0;
		int left = input.length() - 1;

		while (right <= left) {

			if (input.charAt(right) != input.charAt(left)) {
				return false;
			}

			right++;
			left--;
		}

		return true;
	}

}

Output:
Is hello palindrome? false
Is abcba palindrome? true

3. Java Check String Palindrome - for loop


Can we reduce no of lines from the above code? Yes by using for loop.
package com.javaprogramto.programs.strings.palindrome;

public class StringCheckPalindrome2 {

	public static void main(String[] args) {

		String input1 = "hello";
		boolean isPalindrome = isPalindromeWithForLoop(input1);
		System.out.println("Is " + input1 + " palindrome? " + isPalindrome);

		String input2 = "abcba";
		isPalindrome = isPalindromeWithForLoop(input2);
		System.out.println("Is " + input2 + " palindrome? " + isPalindrome);
	}

	private static boolean isPalindromeWithForLoop(String input) {
		
		int length = input.length();
		for (int i = 0; i < length; i++) {

			if (input.charAt(i) != input.charAt(length - i - 1)) {
				return false;
			}

		}

		return true;
	}

}

This code generates the same about as same as 2 pointer example.

4. Java Check String Palindrome - StringBuilder


Next, Can we reduce the above code to single line ? Answer is yes. It is done with the help of StringBuilder class and using its reverse() method.

reverse() method is to reverse the given input string and then compares it with the original input string.

	private static boolean isPalindromeWithStringBuilder(String input) {

		return input.equals(new StringBuilder(input).reverse().toString());
	}


This code also work without any errors and produces the same output.

5. Java 8 Program To Check String Palindrome 


Next, We'll see how to check the string palindrome in java 8 functional style programming.

Call IntStream.range() method with 0 to length/2. This is like running a loop from string index 0 to its length/2.

Next, call noneMatch() method with the predicate condition. This method returns true if no value is matched to the given predicate.

The solution can be implemented in a single line to make the code clean.

Look at the below code.
package com.javaprogramto.programs.strings.palindrome;

import java.util.stream.IntStream;

public class StringCheckPalindrome4 {

	public static void main(String[] args) {

		String input1 = "hello";
		boolean isPalindrome = isPalindromeInJava8(input1);
		System.out.println("Is " + input1 + " palindrome? " + isPalindrome);

		String input2 = "abcba";
		isPalindrome = isPalindromeInJava8(input2);
		System.out.println("Is " + input2 + " palindrome? " + isPalindrome);
	}

	private static boolean isPalindromeInJava8(String input) {

		return IntStream.range(0, input.length() / 2)
				.noneMatch(index -> input.charAt(index) != input.charAt(input.length() - index - 1));

	}

}

6. Conclusion


In this article, We've seen how to check the string is palindrome or not in older java and new java 8 streams api.



Monday, November 8, 2021

Java 8 - Generate All Permutations of String

1. Overview

In this tutorial, We'll learn how to get and print all permutations of string in java. This can be solved in iterative and recursive approaches.

Iterative approach is much complex and recursive approach is simple to code.


Let us explore the examples in before java and with java 8 parallel streams.

For example input is ABC and output permutations are ABC, ACB, BCA, BAC, CAB, CBA.

Java 8 - Generate All Permutations of String


2. Java Generate All Permutations of String - Recursive


Understand the logic from the below diagram.

Java Generate All Permutations of String - Recursive

The initial state contains the initial string and each successive state can be computed by the following formula. each letter of the string will become the first letter of the string (swap positions) and then permute all of the remaining letters using a recursive call. 

package com.javaprogramto.programs.strings.permutations;

public class StringPermutationsExample1 {

	public static void main(String[] args) {

		stringPermuteAndPrint("", "ABC");
	}

	private static void stringPermuteAndPrint(String prefix, String str) {
		int n = str.length();
		if (n == 0) {
			System.out.print(prefix + " ");
		} else {
			for (int i = 0; i < n; i++) {
				stringPermuteAndPrint(prefix + str.charAt(i), str.substring(i + 1, n) + str.substring(0, i));
			}
		}
	}

}


Output:
ABC ACB BCA BAC CAB CBA 
At the beginning of the method, prefix is empty. For each iteration, prefix will be added with the next character from input string. And the remaining the characters of the string are passed to the recursive call. This chain is invoked till the last character of the string.

Here, all possible combinations are printed on the console. Instead of this, we can store all of these values into a Set or List. List is better than Set because Set removes the duplicates.

For example, input TEST output will have the duplicates. So to hold the duplicates which are valid ones, we need to use the List instance.


3. Java 8 Generate All Permutations of String - Recursive


Next, let us use the java 8 streams and parallel executions for the larger inputs values.

Here, we use IntStream.range(0, n) method to run the for loop through from 0 to string length such as n.
Parallel() method to run the calls parallel for next character of string.
package com.javaprogramto.programs.strings.permutations;

import java.util.stream.IntStream;

public class StringPermutationsExample2 {

	public static void main(String[] args) {

		stringPermuteAndPrint("", "ABC");

	}

	// java 8 stream example
	private static void stringPermuteAndPrint(String prefix, String str) {
		int n = str.length();
		if (n == 0) {
			System.out.print(prefix + " ");
		} else {
			IntStream.range(0, n).parallel().forEach(
					i -> stringPermuteAndPrint(prefix + str.charAt(i), str.substring(i + 1, n) + str.substring(0, i)));
		}
	}

}

This program also produces the same output as before java 8 example.


4. Conclusion


In this article, We've seen how to get all permutations of string in java and java 8 streams.



Java - Joining Multiple Strings With a Delimiter

1. Overview

In this tutorial, We'll learn how to join the multiple strings with a delimiter in java programming.

Joining strings can be done in several ways with the given separator.

Before java 8, this is solved with the StringBuilder class. But, the same can be solved in 3 ways in java 8 or later.

Let us jump into the example programs on each solution.
Java - Joining Multiple Strings With a Delimiter



2. Java Joining Strings With Delimiter - StringBuilder


StringBuilder is a class that built on the Builder pattern and this is not synchronized.

By using this class, we run the for loop and add the each string and delimiter using append() method.

Look into the below example. Here we are using var-args concept.
package com.javaprogramto.programs.strings.joining;

public class JoiningStringDelimiterExample1 {

	public static void main(String[] args) {

		// input 1
		String output1 = joinStringsWithDelimiter("-", "hello", "world", "welcome", "to", "java", "programs");
		System.out.println("Ouptut 1 : " + output1);

		// input 1
		String output2 = joinStringsWithDelimiter("**", "this", "is", "second", "input");
		System.out.println("Ouptut 2 : " + output2);

	}

	/**
	 * Gets the joined string for the input strings with a given delimiter
	 * 
	 * @param delimiter
	 * @param strings
	 * @return
	 */
	private static String joinStringsWithDelimiter(String delimiter, String... strings) {

		StringBuilder stringBuilder = new StringBuilder();
		int index = 0;
		for (index = 0; index < strings.length - 1; index++) {

			stringBuilder.append(strings[index]).append(delimiter);
		}

		stringBuilder.append(strings[index]);

		return stringBuilder.toString();
	}

}

Output:
Ouptut 1 : hello-world-welcome-to-java-programs
Ouptut 2 : this**is**second**input

Any no of strings and any delimiter can be passed to this program. And also, StringBuffer can be used in-place of StringBuilder but StringBuffer is slow because of thread safe.

3. Java 8 Joining Strings With Delimiter - StringJoiner


One of the ways in java 8 is using StringJoiner class and this is a string utility class.

StringJoiner class can be used to construct the set of strings with the delimiter.

Look at the below example program.
package com.javaprogramto.programs.strings.joining;

import java.util.StringJoiner;

public class JoiningStringDelimiterExample2 {

	public static void main(String[] args) {

		// input 1
		String output1 = stringJoinerWithDelimiter("-", "hello", "world", "welcome", "to", "java", "programs");
		System.out.println("Ouptut 1 : " + output1);

		// input 1
		String output2 = stringJoinerWithDelimiter("**", "this", "is", "second", "input");
		System.out.println("Ouptut 2 : " + output2);

	}

	private static String stringJoinerWithDelimiter(String delimiter, String... strings) {

		StringJoiner stringJoinder = new StringJoiner(delimiter);
		for (String str : strings) {

			stringJoinder.add(str);
		}

		return stringJoinder.toString();
	}

}

This program produces the same output as above section example.

And alos this supports for adding the suffix and prefix. But these are optional functionality.
StringJoiner stringJoinder = new StringJoiner(delimiter, "!!", "!!");
Output:
Ouptut 1 : !!hello-world-welcome-to-java-programs!!
Ouptut 2 : !!this**is**second**input!!

4. Java 8 Joining Strings With Delimiter - String.join()


String class is added with join() method in java 8. This function reduces the lots of boiler plate coding in the applications now.

String.join() method takes the delimiter and a set of strings.

And alos optionally prefix and suffix also can be passed to join() method.
package com.javaprogramto.programs.strings.joining;

public class JoiningStringDelimiterExample3 {

	public static void main(String[] args) {

		// input 1
		String output1 = stringJoinWithDelimiter("-", "hello", "world", "welcome", "to", "java", "programs");
		System.out.println("Ouptut 1 : " + output1);

		// input 1
		String output2 = stringJoinWithDelimiter("**", "this", "is", "second", "input");
		System.out.println("Ouptut 2 : " + output2);

	}

	private static String stringJoinWithDelimiter(String delimiter, String... strings) {

		return String.join(delimiter, strings);
	}
}

This example also generates the same output.

5. Java 8 Joining Strings With Delimiter - Collectors.joining()


Java 8 stream api is added with very useful method Collectors.joining() method.

Collectors.joining() method should be passed to the collect() method. So that String can be retrieved from joining() output.

Look at the below sample code.
import java.util.Arrays;
import java.util.stream.Collectors;

public class JoiningStringDelimiterExample4 {

	public static void main(String[] args) {

		// input 1
		String output1 = stringCollectorsJoiningWithDelimiter("-", "hello", "world", "welcome", "to", "java",
				"programs");
		System.out.println("Ouptut 1 : " + output1);

		// input 1
		String output2 = stringCollectorsJoiningWithDelimiter("**", "this", "is", "second", "input");
		System.out.println("Ouptut 2 : " + output2);

	}

	private static String stringCollectorsJoiningWithDelimiter(String delimiter, String... strings) {

		String output = Arrays.stream(strings).collect(Collectors.joining(delimiter));

		return output;
	}
}

The generated output is same for this example also.

6. Java 8 Joining Strings With Delimiter - Third Party Libraries


Third party api's also provide the support for this functionality from apache commons lang StringUtils.join() and guava Joiner class.
import org.apache.commons.lang3.StringUtils;

public class JoiningStringDelimiterExample5 {

	public static void main(String[] args) {
	// same code as abvoe example
	}

	private static String stringCollectorsJoiningWithDelimiter(String delimiter, String... strings) {

		String output = StringUtils.join(strings, delimiter);

		return output;
	}
}


7. Conclusion


In this article, We've seen how many ways string joining is possible in older java, java 8 and third party apis.

But the String joining strictly discouraged using "+=" operator as below.
String out = "";

for (int i = 0; i < 100000; i++) {
	out += "new value";
}

Because, this code reconstructs many strings with "+=" operation which over kills the memory and prone to performance issues. Finally, this code execution will be much slower than StringBuilder.