Skip to content

Commit 1d798e0

Browse files
committed
Finding first duplicate element in a string
1 parent ff12288 commit 1d798e0

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import java.util.Arrays;
2+
import java.util.LinkedHashMap;
3+
import java.util.function.Function;
4+
import java.util.stream.Collectors;
5+
6+
public class FirstDuplicateElementFromAString {
7+
8+
public static void main(String[] args) {
9+
10+
String phrase = "this is the best day of my life";
11+
12+
String firstDuplicateElement = Arrays.stream(phrase.trim().split(""))
13+
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
14+
.entrySet()
15+
.stream()
16+
.filter(x -> x.getValue() > 1)
17+
.findFirst().get().getKey();
18+
19+
System.out.println("The first duplicate element: " + firstDuplicateElement);
20+
}
21+
}

0 commit comments

Comments
 (0)