Showing posts with label java 8 Stream Examples. Show all posts
Showing posts with label java 8 Stream Examples. Show all posts

Saturday, November 27, 2021

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

Friday, November 26, 2021

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


Wednesday, November 24, 2021

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

Tuesday, November 23, 2021

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

Saturday, November 13, 2021

Java 8 Collectors.toMap() - Collectors to map Examples

1. Overview

In this tutorial, We'll learn the usage of toMap() method of the Collectors class that is added in the jdk 8.

toMap() method is a static method from Collectors class from java 8 onwards.

Collectors.toMap() method is used to convert the stream of object into the Map as needed with the help 3 overloaded methods.
Java 8 Collectors.toMap() - Collectors to map Examples


2. Collectos.toMap() Syntax


toMap() method syntax from java 8 api.
public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
                                                    Function<? super T,? extends U> valueMapper)

public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
                                                    Function<? super T,? extends U> valueMapper,
                                                    BinaryOperator<U> mergeFunction)
													
public static <T,K,U,M extends Map<K,U>> Collector<T,?,M> toMap(Function<? super T,? extends K> keyMapper,
                                                                Function<? super T,? extends U> valueMapper,
                                                                BinaryOperator<U> mergeFunction,
                                                                Supplier<M> mapSupplier)


3. Collectors toMap() To Convert List to Map


If we have list of objects such as List of strings and this list has to be converted into the map. In the Map, key is the string and value is its length.

Look at the below code how Collectos.toMap() method can be used to transform List to Map.
package com.javaprogramto.java8.collectors.tomap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CollectorsToMapExample {

	public static void main(String[] args) {
		List<String> numbersinStringList = new ArrayList<>();

		numbersinStringList.add("One");
		numbersinStringList.add("Two");
		numbersinStringList.add("Three");
		numbersinStringList.add("Four");
		numbersinStringList.add("Five");

		Map<String, Integer> map = numbersinStringList.stream()
				.collect(Collectors.toMap(Function.identity(), String::length));
		System.out.println("List : "+numbersinStringList);
		System.out.println("Map : "+map);

	}

}

Output:
List : [One, Two, Three, Four, Five]
Map : {Five=4, One=3, Four=4, Two=3, Three=5}


4. Collectors toMap To Convert List to Map Using Custom Objects


In the previous section, example is based on the List of Strings. But in the realtime applications, we mostly working with the collection of obejcts. Those objects can be any type of user defined types.

So, to handle custom objects with toMap() method is little tricky.

Let us look at the below program that we are going to add the Employee objects to List first and next converting into a map with key as emp id and value is full emp object.


Employee class
package com.javaprogramto.java8.compare;

import java.util.Objects;

public class Employee {

    private int id;
    private String name;
    private int age;

    public Employee(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return id == employee.id &&
                age == employee.age &&
                Objects.equals(name, employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, age);
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                "} \n";
    }
}

toMap() method with Custom objects:
package com.javaprogramto.java8.collectors.tomap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.javaprogramto.java8.compare.Employee;

public class CollectorsToMapExample2 {

	public static void main(String[] args) {
		List<Employee> employeeList = new ArrayList<>();

		employeeList.add(new Employee(1, "One", 20));
		employeeList.add(new Employee(2, "Two", 30));
		employeeList.add(new Employee(3, "Three", 40));
		employeeList.add(new Employee(4, "Four", 25));
		employeeList.add(new Employee(5, "Give", 35));
		
		Map<Integer, Employee> map = employeeList.stream()
				.collect(Collectors.toMap(Employee::getId, Function.identity()));
		
		
		System.out.println("List : "+employeeList);
		System.out.println("Map : "+map);

	}

}

Output:
List : [Employee{id=1, name='One', age=20} 
, Employee{id=2, name='Two', age=30} 
, Employee{id=3, name='Three', age=40} 
, Employee{id=4, name='Four', age=25} 
, Employee{id=5, name='Give', age=35} 
]
Map : {1=Employee{id=1, name='One', age=20} 
, 2=Employee{id=2, name='Two', age=30} 
, 3=Employee{id=3, name='Three', age=40} 
, 4=Employee{id=4, name='Four', age=25} 
, 5=Employee{id=5, name='Give', age=35} 
}


This program compiles and executes without any errors.

You can see the map is with emp id as key and emp object as value.


5. Collectors toMap To Convert List to Map Using Custom duplicate keys


The above section program works flawlessly when all emp id's are unique. What happens if the list has the same employee instance added twice or more.

Just add the below code to the program and run it.
employeeList.add(new Employee(5, "Give", 35));
employeeList.add(new Employee(5, "Give", 35));
Executin is failed with the error "Exception in thread "main" java.lang.IllegalStateException: Duplicate key 5"


It is clearly saying deplicate key with value 5.

How to handle these type of cases when using stream collectors tomap() method. 
When the same key is added to the HashMap, it does not show up any error. It replaces the exisitng value with the new one for the duplicate key.

To achive these behaviour, we need to use toMap() overloaded method with thrid argument BinaryOperator.

Look at the beloe code.
package com.javaprogramto.java8.collectors.tomap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.javaprogramto.java8.compare.Employee;

public class CollectorsToMapExample3 {

	public static void main(String[] args) {
		List<Employee> employeeList = new ArrayList<>();

		employeeList.add(new Employee(1, "One", 20));
		employeeList.add(new Employee(2, "Two", 30));
		employeeList.add(new Employee(3, "Three", 40));
		employeeList.add(new Employee(4, "Four", 25));
		employeeList.add(new Employee(5, "Give", 35));
		employeeList.add(new Employee(5, "Giver", 36));

		Map<Integer, Employee> map = employeeList.stream()
				.collect(Collectors.toMap(Employee::getId, Function.identity(), (oldVal, newVal) -> newVal));

		System.out.println("List : " + employeeList);
		System.out.println("Map : " + map);

	}

}

Output:
List : [Employee{id=1, name='One', age=20} 
, Employee{id=2, name='Two', age=30} 
, Employee{id=3, name='Three', age=40} 
, Employee{id=4, name='Four', age=25} 
, Employee{id=5, name='Give', age=35} 
, Employee{id=5, name='Giver', age=36} 
]
Map : {1=Employee{id=1, name='One', age=20} 
, 2=Employee{id=2, name='Two', age=30} 
, 3=Employee{id=3, name='Three', age=40} 
, 4=Employee{id=4, name='Four', age=25} 
, 5=Employee{id=5, name='Giver', age=36} 
}

6. Collectors toMap To Other Map Types


As of now we wrote the examples. In all of these returned map is HashMap. That means toMap() method returns HashMap by default.

If we want to convert into the different Map implmentation then we need to use another overloaded method of toMap() with 4th argument Supplier.

Look at the below examples to convert the list into TreeMap and ConcurrentHashMap.

TreeMap is a sorted map by key where as ConcurrentHashMap works in multithreaded enviornments.
package com.javaprogramto.java8.collectors.tomap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.javaprogramto.java8.compare.Employee;

public class CollectorsToMapExample4 {

	public static void main(String[] args) {
		List<Employee> employeeList = new ArrayList<>();

		employeeList.add(new Employee(1, "One", 20));
		employeeList.add(new Employee(2, "Two", 30));
		employeeList.add(new Employee(3, "Three", 40));
		employeeList.add(new Employee(4, "Four", 25));
		employeeList.add(new Employee(5, "Give", 35));
		employeeList.add(new Employee(5, "Giver", 36));

		// TreeMap example
		// converting duplicate keys into the TreeMap
		Map<Integer, Employee> treeMap = employeeList.stream().collect(
				Collectors.toMap(Employee::getId, Function.identity(), (oldVal, newVal) -> newVal, TreeMap::new));

		System.out.println("ArrayList : " + employeeList);
		System.out.println("TreeMap : " + treeMap);

		// ConcurrentHashMap example
		// converting duplicate keys into the ConcurrentHashMap
		Map<Integer, Employee> concurrentHashMap = employeeList.stream().collect(Collectors.toMap(Employee::getId,
				Function.identity(), (oldVal, newVal) -> newVal, ConcurrentHashMap::new));

		System.out.println("ArrayList : " + employeeList);
		System.out.println("ConcurrentHashMap : " + concurrentHashMap);

	}

}


7. Conclusion


In this article, We've seen how to use Collectors.toMap() method and how to handle the duplicate keys in Map when the source list is with duplicates.

How to convert the stream into TreeMap or any other Map types.





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 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.



Saturday, August 15, 2020

Java 8 and Infinite Streams - How To Create Infinite Streams

1. Overview

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

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

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

Java 8 and Infinite Streams - How To Create Infinite Streams

Sunday, August 9, 2020

How To Compare Two Objects In Java 8 For Equality

1. Overview


In this article,  You'll learn how to compare two objects in the java. In many of the cases, you might need to compare the two same types of objects that are having the same values for all instance variables.

How To Compare Two Objects In Java 8 For Equality