Java Stream How to - Compare the thread name for filter and map and foreach method








Question

We would like to know how to compare the thread name for filter and map and foreach method.

Answer

import java.util.Arrays;
import java.util.List;
/*from   www.  j a v  a  2 s .  c  o  m*/
public class Main {

  public static void main(String[] args) throws Exception {
    List<String> strings = Arrays.asList("a1", "a2", "b1", "c2", "c1");

    strings
    .parallelStream()
    .filter(s -> {
        System.out.format("filter:  %s [%s]\n", s, Thread.currentThread().getName());
        return true;
    })
    .map(s -> {
        System.out.format("map:     %s [%s]\n", s, Thread.currentThread().getName());
        return s.toUpperCase();
    })
    .forEach(s -> System.out.format("forEach: %s [%s]\n", s, Thread.currentThread().getName()));

  }
}

The code above generates the following result.