-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindFirstNonDuplicate.java
More file actions
37 lines (30 loc) · 1.28 KB
/
FindFirstNonDuplicate.java
File metadata and controls
37 lines (30 loc) · 1.28 KB
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
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
/**
* Inspired by a not-so-elegant example solution that I saw online.
*
* This implementation only needs to pass through the input String once, as LinkedHashMap preserves ordering.
*/
public class FindFirstNonDuplicate {
public static void main(String args[]) {
String input = "Some text with some letters in it. So how did it go?";
Optional<Character> firstNonDup = firstNonDuplicate(input);
if (firstNonDup.isPresent()) {
System.out.println("Found first non-duplicate character '" + firstNonDup.get() + "'");
} else {
System.out.println("Sorry, there were no non-duplicate characters.");
}
}
// Returns Optional of first non duplicate character if one exists
private static Optional<Character> firstNonDuplicate(String input) {
LinkedHashMap<Character, Integer> characterOccurences = new LinkedHashMap<>();
for (Character c : input.toCharArray()) {
characterOccurences.put(c, characterOccurences.getOrDefault(c, 0) + 1);
}
return characterOccurences.entrySet().stream()
.filter(e -> e.getValue() == 1)
.findFirst()
.map(Map.Entry::getKey);
}
}