forked from raj-ravan/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings.java
More file actions
32 lines (22 loc) · 925 Bytes
/
strings.java
File metadata and controls
32 lines (22 loc) · 925 Bytes
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
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class DistinctCharsCount {
public static void main(String[] args) {
printDistinctCharsWithCount("abc");
printDistinctCharsWithCount("abcab3");
printDistinctCharsWithCount("hi there, i am pankaj");
}
private static void printDistinctCharsWithCount(String input) {
Map<Character, Integer> charsWithCountMap = new HashMap<>();
// using Map merge method from Java 8
for (char c : input.toCharArray())
charsWithCountMap.merge(c, 1, Integer::sum);
System.out.println(charsWithCountMap);
// another way using latest Java enhancements and no for loop, a bit complex though
List<Character> list = input.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
list.stream().forEach(c -> charsWithCountMap.merge(c, 1, Integer::sum));
System.out.println(charsWithCountMap);
}
}