In this tutorial, we will see “How to find Duplicate Characters and their count in a String using Java 8?”
Find Duplicate Characters in String in Java 8
Java 8 – How to find Duplicate Characters and their Count in a String? Share on X
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 | /** * Find Duplicate Characters in String using Java 8 Stream * @author Deepak Verma * */ import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; public class Find_Duplicate_Characters_In_String_Java8_Example { public static void main(String[] args) { String sampleString = "Techndeck"; checkDuplicateCharacters(sampleString); } public static void checkDuplicateCharacters(String sampleString) { Map<Character, Long> characterCount = sampleString.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting())); characterCount.entrySet().stream() .filter(c -> c.getValue() > 1) .forEach(c -> System.out.printf("Duplicate Character - %s \ncount - %d %n", c.getKey(), c.getValue())); } } |
Output:
1 2 3 4 | Duplicate Character - e count - 2 Duplicate Character - c count - 2 |
check if text or string present in a file using java 8
In above example, we first uses the chars()
method to generate a stream of the characters in the original string. Then we uses the mapToObj
method to convert the int values of the characters to their corresponding char values. After that, we uses the groupingBy
collector to group the characters by their value, creating a map where the keys are the unique characters in the string and the values are the number of occurrences of each character. And at last, we filters the map to only include characters that occur more than once and then using the forEach
method, prints out the duplicate characters and their count.
Find Duplicate Characters in String in Java 8
skip method java 8 stream
Java 8 – How to find Duplicate Characters and their Count in a String? Share on X
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: