forked from algorithm010/algorithm010
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCAPCO.java
More file actions
66 lines (53 loc) · 1.97 KB
/
CAPCO.java
File metadata and controls
66 lines (53 loc) · 1.97 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package Interview;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CAPCO {
public static void main(String[] args) {
if ("s" instanceof String)
System.out.println(1);
}
public static String uniqueString_1(List<String> words) {
LinkedHashMap<String, Integer> map = new LinkedHashMap<>(words.size());
for (String s : words) {
Integer count = map.getOrDefault(s, 0);
map.put(s, count + 1);
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return "";
}
public static String uniqueString_2(List<String> words) {
Map<String, Long> stringCountMap = words.stream()
.collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()));
for (String s : stringCountMap.keySet()) {
if (stringCountMap.get(s) == 1) {
return s;
}
}
return "";
}
public static String uniqueString(List<String> words) {
// return words.stream()
// .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
// .entrySet()
// .stream()
// .filter(entry -> entry.getValue() == 1)
// .findFirst()
// .map(Map.Entry::getKey)
// .orElse(null);
StringBuilder result = new StringBuilder();
words.stream()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet()
.stream()
.filter(entry -> entry.getValue() == 1)
.findFirst()
.ifPresent(entry -> result.append(entry.getKey()));
return result.toString();
}
}