MCPcopy Index your code
hub / github.com/BruceEckel/OnJava8-Examples / CountMap

Class CountMap

onjava/CountMap.java:11–67  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

9import java.util.stream.*;
10
11public class CountMap
12extends AbstractMap<Integer,String> {
13 private int size;
14 private static char[] chars =
15 "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
16 private static String value(int key) {
17 return
18 chars[key % chars.length] +
19 Integer.toString(key / chars.length);
20 }
21 public CountMap(int size) {
22 this.size = size < 0 ? 0 : size;
23 }
24 @Override public String get(Object key) {
25 return value((Integer)key);
26 }
27 private static class Entry
28 implements Map.Entry<Integer,String> {
29 int index;
30 Entry(int index) { this.index = index; }
31 @Override public boolean equals(Object o) {
32 return o instanceof Entry &&
33 Objects.equals(index, ((Entry)o).index);
34 }
35 @Override public Integer getKey() { return index; }
36 @Override public String getValue() {
37 return value(index);
38 }
39 @Override public String setValue(String value) {
40 throw new UnsupportedOperationException();
41 }
42 @Override public int hashCode() {
43 return Objects.hashCode(index);
44 }
45 }
46 @Override
47 public Set<Map.Entry<Integer,String>> entrySet() {
48 // LinkedHashSet retains initialization order:
49 return IntStream.range(0, size)
50 .mapToObj(Entry::new)
51 .collect(Collectors
52 .toCollection(LinkedHashSet::new));
53 }
54 public static void main(String[] args) {
55 final int size = 6;
56 CountMap cm = new CountMap(60);
57 System.out.println(cm);
58 System.out.println(cm.get(500));
59 cm.values().stream()
60 .limit(size)
61 .forEach(System.out::println);
62 System.out.println();
63 new Random(47).ints(size, 0, 1000)
64 .mapToObj(cm::get)
65 .forEach(System.out::println);
66 }
67}
68/* Output:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected