How to find duplicate elements from string using Java8?

Gain Java Knowledge
1 min readAug 6, 2023

In this tutorial, we will learn How to filter out duplicate characters in Java 8.

First we will split string based on “” empty string value and will store into Array of string and after that we will use Arrays.Stream(-) method and convert into stream and after converting into stream we can call .collect(-) method.Inside collect(-) method we can pass the parameter Collectors.groupingBy(-,-) and Inside Collectors.groupingBy(-,-) function we can pass the two parameters one is Function.identity() to find the unique identity of each element and second parameter we can paas Collectors.counting() to count the number of occurrence for each character. After that we again need to convert Map into stream to apply stream functions. So we can call .entrySet().stream() and now we can apply the filter and restrict the data based on condition .filter(ele -> ele.getValue() > 1) . Now we will store all the duplicate keys into ArrayList and print the duplicateElements.

Below is the complete Code :

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

public class FindDuplicateCharFromString {

public static void main(String[] args) {

String input = "gainjavaknowledge";

List<String> duplicateElements = Arrays.stream(input.split(""))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()…

--

--

Gain Java Knowledge
Gain Java Knowledge

Written by Gain Java Knowledge

The Java programming language is one of the most popular languages today. Stay up to date with news, certifications, free learning resources and much more.

No responses yet