Debian Codegraph @

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

raw
1 package com.carrotsearch.hppc.examples;
2
3 import org.junit.Test;
4
5 import com.carrotsearch.hppc.IntIntHashMap;
6 import com.carrotsearch.hppc.procedures.IntIntProcedure;
7
8 /**
9 * An example of plucking a value from an anonymous inner class.
10 */
11 public class HppcExample_005_ForEachValues {
12 @Test
13 public void forEach_FilteredCounting() {
14 // Create a map of key-value pairs.
15 final IntIntHashMap map = new IntIntHashMap();
16 map.put(1, 2);
17 map.put(2, -5);
18 map.put(3, 10);
19 map.put(4, -1);
20
21 // And count only non-negative values. Note the "counter"
22 // is physically part of the anonymous inner class but we can
23 // access it because of how forEach is declared (it returns the exact
24 // subclass type of the argument).
25
26 int count = map.forEach(new IntIntProcedure() {
27 int counter;
28
29 public void apply(int key, int value) {
30 if (value >= 0) {
31 counter++;
32 }
33 }
34 }).counter;
35
36 System.out.println("There are " + count + " values that are non-negative.");
37 }
38 }