Debian Codegraph @

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

raw
1 package com.carrotsearch.hppc.examples;
2
3 import static com.carrotsearch.hppc.examples.Helpers.*;
4
5 import java.util.Iterator;
6
7 import org.junit.Before;
8 import org.junit.Test;
9
10 import com.carrotsearch.hppc.IntArrayDeque;
11 import com.carrotsearch.hppc.cursors.IntCursor;
12 import com.carrotsearch.hppc.procedures.IntProcedure;
13
14 /**
15 * Examples of how to iterate over HPPC deques.
16 */
17 public class HppcExample_002_IteratingOverDeques {
18
19 public IntArrayDeque deque;
20
21 @Before
22 public void setup() {
23 deque = new IntArrayDeque();
24 deque.addLast(1, 1, 2, 3, 5);
25 }
26
27 /**
28 * All deques implement {@link Iterable} interface that returns a "cursor"
29 * object that moves over the container's elements. The cursor object remains
30 * identical for the entire iteration (very little memory overhead).
31 *
32 * The cursor's index points at the underlying buffer's position of a
33 * given element.
34 */
35 @Test
36 public void cursorFirstToLast() {
37 for (IntCursor c : deque) {
38 printfln("deque[%d] = %d", c.index, c.value);
39 }
40 }
41
42 /**
43 * Reverse order iterator (cursor).
44 */
45 @Test
46 public void cursorLastToFirst() {
47 for (Iterator<IntCursor> i = deque.descendingIterator(); i.hasNext();) {
48 IntCursor c = i.next();
49 printfln("deque[%d] = %d", c.index, c.value);
50 }
51 }
52
53 /**
54 * A for-each type loop with an anonymous class.
55 */
56 @Test
57 public void forEachLoop() throws Exception {
58 deque.forEach(new IntProcedure() {
59 public void apply(int value) {
60 printfln("deque[?] = %d", value);
61 }
62 });
63 }
64
65 /**
66 * A for-each type loop with an anonymous class.
67 */
68 @Test
69 public void forEachLoopReversed() throws Exception {
70 deque.descendingForEach(new IntProcedure() {
71 public void apply(int value) {
72 printfln("deque[?] = %d", value);
73 }
74 });
75 }
76 }