Letter frequency: Difference between revisions
Content added Content deleted
m (→{{header|Lua}}) |
|||
Line 3,401: | Line 3,401: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
This implementation will capture the frequency of all characters |
|||
<syntaxhighlight lang="java5"> |
|||
import java.io.FileInputStream; |
|||
import java.io.IOException; |
|||
import java.io.InputStreamReader; |
|||
import java.util.HashMap; |
|||
import java.util.Map; |
|||
</syntaxhighlight> |
|||
<syntaxhighlight lang="java5"> |
|||
public static void main(String[] args) throws IOException { |
|||
Map<Integer, Integer> frequencies = frequencies("src/LetterFrequency.java"); |
|||
System.out.println(print(frequencies)); |
|||
} |
|||
static String print(Map<Integer, Integer> frequencies) { |
|||
StringBuilder string = new StringBuilder(); |
|||
int key; |
|||
for (Map.Entry<Integer, Integer> entry : frequencies.entrySet()) { |
|||
key = entry.getKey(); |
|||
string.append("%,-8d".formatted(entry.getValue())); |
|||
/* display the hexadecimal value for non-printable characters */ |
|||
if ((key >= 0 && key < 32) || key == 127) { |
|||
string.append("%02x%n".formatted(key)); |
|||
} else { |
|||
string.append("%s%n".formatted((char) key)); |
|||
} |
|||
} |
|||
return string.toString(); |
|||
} |
|||
static Map<Integer, Integer> frequencies(String path) throws IOException { |
|||
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(path))) { |
|||
/* key = character, and value = occurrences */ |
|||
Map<Integer, Integer> map = new HashMap<>(); |
|||
int value; |
|||
while ((value = reader.read()) != -1) { |
|||
if (map.containsKey(value)) { |
|||
map.put(value, map.get(value) + 1); |
|||
} else { |
|||
map.put(value, 1); |
|||
} |
|||
} |
|||
return map; |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
<pre> |
|||
44 0a |
|||
463 |
|||
1 ! |
|||
8 " |
|||
5 % |
|||
2 & |
|||
33 ( |
|||
33 ) |
|||
4 * |
|||
1 + |
|||
9 , |
|||
3 - |
|||
29 . |
|||
5 / |
|||
2 0 |
|||
4 1 |
|||
3 2 |
|||
1 3 |
|||
1 7 |
|||
1 8 |
|||
1 : |
|||
19 ; |
|||
7 < |
|||
12 = |
|||
7 > |
|||
2 B |
|||
4 E |
|||
4 F |
|||
2 H |
|||
18 I |
|||
2 K |
|||
2 L |
|||
8 M |
|||
3 O |
|||
3 R |
|||
13 S |
|||
1 V |
|||
1 [ |
|||
1 ] |
|||
73 a |
|||
3 b |
|||
28 c |
|||
19 d |
|||
121 e |
|||
13 f |
|||
25 g |
|||
11 h |
|||
53 i |
|||
6 j |
|||
8 k |
|||
25 l |
|||
22 m |
|||
67 n |
|||
24 o |
|||
44 p |
|||
8 q |
|||
81 r |
|||
30 s |
|||
87 t |
|||
34 u |
|||
15 v |
|||
7 w |
|||
5 x |
|||
20 y |
|||
11 { |
|||
2 | |
|||
11 } |
|||
</pre> |
|||
<br /> |
|||
{{works with|Java|5+}} |
{{works with|Java|5+}} |
||
<syntaxhighlight lang="java5">import java.io.BufferedReader; |
<syntaxhighlight lang="java5">import java.io.BufferedReader; |