How to iterate over stream and increment index value in Lambda Expression?
UPDATED: 03 July 2015
Tags:
Stream
,
stream-api
Many of you having trouble for increment index value inside Lambda expression because of Local variable index defined in an enclosing scope must be final or effectively final. There is an alternative for that...
java.util.concurrent.atomic.AtomicInteger
An int value that may be updated atomically. See the java.util.concurrent.atomic package specification for description of the properties of atomic variables. An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an java.lang.Integer. However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.
Java doc
Java doc
Source Code
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class LambdaIncrementIndexExample { public static void main(String[] args) { /* AtomicInteger in `stream()` */ new LambdaIncrementIndexExample().UsingStream(); /* AtomicInteger in `parallelStream()` */ new LambdaIncrementIndexExample().UsingParallelStream(); } /** * Example of using AtomicInteger in `stream()` */ public void UsingStream() { /* Create object of AtomicInteger with initial value `0` */ AtomicInteger atomicInteger = new AtomicInteger(0); /* Create list of names. */ List<String> listNames = new ArrayList<String>(Arrays.asList("Vicky Thakor", "Chirag Thakor", "Dave Hill", "Finn Jones", "Heer Thakor")); listNames.stream() .filter(name -> name.endsWith("Thakor")) .forEach(name -> { /* Get the previous value of count and increment it by `1` */ atomicInteger.getAndIncrement(); /* Print the name */ System.out.println(name); }); /* Get value of `atomicInteger` */ System.out.println("Total match found using `stream()`: " + atomicInteger.get()); System.out.println("+++++++++++++++++++++++++++"); } /** * Example of using AtomicInteger in `parallelStream()` */ public void UsingParallelStream() { /* Create object of AtomicInteger with initial value `0` */ AtomicInteger atomicInteger = new AtomicInteger(0); /* Create list of names. */ List<String> listNames = new ArrayList<String>(Arrays.asList("Vicky Thakor", "Chirag Thakor", "Dave Hill", "Finn Jones", "Heer Thakor")); listNames.parallelStream() .filter(name -> name.endsWith("Thakor")) .forEach(name -> { /* Get the previous value of count and increment it by `1` */ atomicInteger.getAndIncrement(); /* Print the name */ System.out.println(name); }); /* Get value of `atomicInteger` */ System.out.println("Total match found using `parallelStream()`: " + atomicInteger.get()); } }
Output
Vicky Thakor Chirag Thakor Heer Thakor Total match found using `stream()`: 3 +++++++++++++++++++++++++++ Heer Thakor Chirag Thakor Vicky Thakor Total match found using `parallelStream()`: 3
Tags:
Stream
,
stream-api
0 comments :