In this post we will learn How to find first non-repeatable character from a String using Java 8?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.kkjavatutorials.client; import static java.util.function.Function.identity; import java.util.LinkedHashMap; import java.util.function.Consumer; import java.util.stream.Collectors; /** * @author KK JavaTutorials * This java program is all about how will you find first non-repeatable character from a String using Java 8 */ public class FindFirstNonRepeatableCharacterInStringTest { public static void main(String[] args) { findFirstNonRepeatingInString("KKJavaTutorials",System.out::println); findFirstNonRepeatingInString("English",System.out::println); } private static void findFirstNonRepeatingInString(String inputText, Consumer<Character> callback) { inputText.chars().mapToObj(i -> Character.valueOf((char) i)) .collect(Collectors.groupingBy(identity(), LinkedHashMap::new, Collectors.counting())).entrySet() .stream().filter(entry -> entry.getValue() == 1L).map(entry -> entry.getKey()).findFirst().map(c -> { callback.accept(c); return c; }); } } |
Sample output of above program:
1 2 |
J E |
You may also like :
How to convert number to words in java
How to swap two numbers with or without temporary variable in java
How to reverse a number in Java
How to check Armstrong number java program
Java program to find factorial of a number
Java Program to Calculate the Power of a Number
That’s all about Java Program to find first non-repeatable character from a String using Java 8 ?
If you have any feedback or suggestion please feel free to drop in blow comment box.