-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDuplicateElementFromAString.java
38 lines (30 loc) · 1.26 KB
/
DuplicateElementFromAString.java
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
29
30
31
32
33
34
35
36
37
38
package com.javaexperiments;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class DuplicateElementFromAString {
public static void main(String[] args) {
String phrase = "life is great and coding is the best";
findDuplicateElements (phrase);
}
/**
* Finds and prints duplicate elements from a given string.
* Spaces are excluded from the computation.
*
* @param phrase The input string to analyze.
*/
private static void findDuplicateElements (String phrase) {
List<String> duplicateElements = Arrays.stream(phrase.split(""))
.filter(character -> !character.isBlank()) // Exclude spaces or blank characters
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) //Function.identity() uses the characters themselves as keys
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1) // Filter elements with count > 1 (duplicates)
.map(Map.Entry::getKey)
.sorted()
.toList();
System.out.println("The duplicate elements are: " + duplicateElements);
}
}