Debian Codegraph @

hppc-examples/src/test/java/com/carrotsearch/hppc/examples/HppcExample_004_IteratingOverMaps.java

raw
1 package com.carrotsearch.hppc.examples;
2
3 import static com.carrotsearch.hppc.examples.Helpers.*;
4 import static org.assertj.core.api.Assertions.*;
5
6 import org.junit.Before;
7 import org.junit.Test;
8
9 import com.carrotsearch.hppc.IntLongHashMap;
10 import com.carrotsearch.hppc.IntLongScatterMap;
11 import com.carrotsearch.hppc.cursors.IntLongCursor;
12 import com.carrotsearch.hppc.procedures.IntLongProcedure;
13
14 /**
15 * Examples of how to iterate over HPPC maps.
16 */
17 public class HppcExample_004_IteratingOverMaps {
18
19 public IntLongHashMap hashMap;
20 public IntLongScatterMap scatterMap;
21
22 @Before
23 public void setup() {
24 // Note that copying the other way around wouldn't be safe (and is thus impossible
25 // because there is no IntLongHashMap constructor that can copy keys from another
26 // container).
27 scatterMap = IntLongScatterMap.from(
28 new int [] {1, 1, 2, 3, 5, 0},
29 new long [] {1, 2, 3, 4, 5, 6});
30
31 hashMap = new IntLongHashMap(scatterMap);
32 }
33
34 /**
35 * All maps implement the {@link Iterable} interface that returns a "cursor"
36 * object that moves over the container's elements. The cursor object remains
37 * identical for the entire iteration (very little memory overhead).
38 *
39 * The cursor's index points at the underlying buffer's position of a
40 * given element, the cursor's key is the key itself and cursor's value is the
41 * value associated with the key.
42 */
43 @Test
44 public void cursor() {
45 for (IntLongCursor c : scatterMap) {
46 printfln("scatterMap %d => %d (at buffer index %d)", c.key, c.value, c.index);
47 assertThat(c.value).isEqualTo(scatterMap.values[c.index]);
48 assertThat(c.key).isEqualTo(scatterMap.keys[c.index]);
49 }
50
51 for (IntLongCursor c : hashMap) {
52 printfln("hashMap %d => %d (at buffer index %d)", c.key, c.value, c.index);
53 assertThat(c.value).isEqualTo(hashMap.values[c.index]);
54 assertThat(c.key).isEqualTo(hashMap.keys[c.index]);
55 }
56 }
57
58 /**
59 * A for-each type loop with an anonymous class.
60 */
61 @Test
62 public void forEachLoop() {
63 scatterMap.forEach(new IntLongProcedure() {
64 @Override
65 public void apply(int key, long value) {
66 printfln("scatterMap %d => %d", key, value);
67 }
68 });
69
70 hashMap.forEach(new IntLongProcedure() {
71 @Override
72 public void apply(int key, long value) {
73 printfln("hashMap %d => %d", key, value);
74 }
75 });
76 }
77 }