Java Streams with Embedded Infinispan

What You Will Learn

How to use the standard Java Streams API on an Infinispan cache to map and reduce cache entries, leveraging Infinispan’s distributed stream support for parallel processing.

Prerequisites

  • Java 17+

Step 1: Add the Embedded Dependency

Add Infinispan core to your pom.xml:

<dependency>
   <groupId>org.infinispan</groupId>
   <artifactId>infinispan-core</artifactId>
</dependency>

Step 2: Create a Cache and Populate It

Create a local cache and store key-value pairs:

      // Construct a simple local cache manager with default configuration
      cm1 = new DefaultCacheManager();
      // Define local cache configuration
      cm1.defineConfiguration("local", new ConfigurationBuilder().build());
      // Obtain the local cache
      cache = cm1.getCache("local");
      // Store some values
      IntStream.range(0, range).boxed().forEach(i -> cache.put(i + "-key", i + "-value"));

Step 3: Map and Reduce with Streams

Use the Streams API on the cache key set to extract numeric prefixes from keys and sum them:

      // Map and reduce the keys
      return cache.keySet().stream()
              .map(e -> Integer.valueOf(e.substring(0, e.indexOf("-"))))
              .collect(() -> Collectors.summingInt(i -> i.intValue()));

The result is 45 (sum of 0 through 9).

Step 4: Run the Tutorial

mvn package exec:java

The output prints Result = 45.

What’s Next