|
1 | 1 | package com.baeldung.string; |
2 | 2 |
|
3 | | -import java.util.HashMap; |
4 | 3 | import java.util.Map; |
| 4 | +import java.util.stream.Collectors; |
5 | 5 | import java.util.stream.IntStream; |
6 | 6 | import java.util.stream.Stream; |
7 | 7 |
|
8 | | -/** |
9 | | - * Created by smatt on 26/05/2017. |
10 | | - */ |
11 | 8 | public class StringToCharStream { |
12 | 9 |
|
13 | | - public StringToCharStream() { |
14 | | - |
15 | | - //let's use the Stream API to manipulate a string |
16 | | - //this will count the occurrence of each character in the test string |
17 | | - |
| 10 | + private StringToCharStream() { |
18 | 11 | String testString = "tests"; |
19 | 12 |
|
20 | | - //first get an IntStream |
21 | 13 | IntStream intStream = testString.chars(); |
22 | 14 | IntStream intStream1 = testString.codePoints(); |
23 | 15 |
|
24 | | - //now let's map them |
25 | 16 | Stream<Character> characterStream = intStream.mapToObj(c -> (char) c); |
26 | 17 | Stream<Character> characterStream1 = intStream1.mapToObj(c -> (char) c); |
27 | 18 |
|
28 | 19 | System.out.println("Counting Occurrence of Letter"); |
29 | | - testString = "Noww"; |
30 | | - |
31 | | - //we don't want to use foreach, so . . . |
32 | | - |
33 | | - Map<Character, Integer> map = new HashMap<>(); |
34 | 20 |
|
35 | | - testString.codePoints() |
36 | | - .mapToObj(c -> (char) c) |
37 | | - .filter(c -> Character.isLetter(c)) |
38 | | - .forEach(c -> { |
39 | | - if(map.containsKey(c)) { |
40 | | - map.put(c, map.get(c) + 1); |
41 | | - } else { |
42 | | - map.put(c, 1); |
43 | | - } |
44 | | - }); |
| 21 | + Map<Character, Integer> map = "Noww".codePoints() |
| 22 | + .mapToObj(c -> (char) c) |
| 23 | + .filter(Character::isLetter) |
| 24 | + .collect(Collectors.toMap(c -> c, c -> 1, Integer::sum)); |
45 | 25 |
|
46 | 26 | //printing out the result here |
47 | 27 | System.out.println(map.toString()); |
48 | 28 |
|
49 | 29 | } |
50 | 30 |
|
51 | | - |
52 | | - public static void main(String [] args) { |
| 31 | + public static void main(String[] args) { |
53 | 32 | new StringToCharStream(); |
54 | 33 | } |
55 | | - |
56 | | - |
57 | 34 | } |
0 commit comments