Executing Streams in Parallel - Java Lambda Stream

Java examples for Lambda Stream:Parallel Stream

Introduction

Use a stream construct on the Collection, and invoke parallelStream().

Demo Code

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    List<Stock> myStocks = new ArrayList<>();
    myStocks.add(new Stock("ORCL", "Oracle", 500.0));
    myStocks.add(new Stock("AAPL", "Apple", 200.0));
    myStocks.add(new Stock("GOOG", "Google", 100.0));
    myStocks.add(new Stock("IBM", "IBM", 50.0));
    myStocks.add(new Stock("MCD", "McDonalds", 300.0));
    // Iterate over each element and print the stock names
    myStocks.stream().forEach(s -> System.out.println(s.getName()));

    boolean allGt = myStocks.parallelStream().allMatch(
        s -> s.getShares() > 100.0);
    System.out.println("All Stocks Greater Than 100.0 Shares? " + allGt);

    // Print out all stocks that have more than 100 shares
    myStocks.parallelStream().filter(s -> s.getShares() > 100.0)
        .forEach(s -> System.out.println(s.getName()));

    Comparator<Stock> byShares = Comparator.comparing(Stock::getShares);
    Stream<Stock> sortedByShares = myStocks.parallelStream().sorted(byShares);
    sortedByShares.forEach(s -> System.out.println("Stock: " + s.getName()
        + " - Shares: " + s.getShares()));

    // May or may not return a value
    Optional<Stock> maybe = myStocks.parallelStream().findFirst();
    System.out.println("First Stock: " + maybe.get().getName());

    List<Stock> newStocks = new ArrayList<>();
    Optional<Stock> maybeNot = newStocks.parallelStream().findFirst();
    Consumer<Stock> myConsumer = (s) -> {
      System.out.println("First Stock (Optional): " + s.getName());
    };/*from   w  w w . j  a  v a 2s .com*/
    maybeNot.ifPresent(myConsumer);

    if (maybeNot.isPresent()) {
      System.out.println(maybeNot.get().getName());
    }

    newStocks.add(new Stock("MCD", "McDonalds", 300.0));
    Optional<Stock> maybeNow = newStocks.stream().findFirst();
    maybeNow.ifPresent(myConsumer);
  }
}

class Stock {
  private String symbol;
  private String name;
  private double shares;

  public Stock(String symbol, String name, double shares) {
    this.symbol = symbol;
    this.name = name;
    this.shares = shares;
  }

  public String getSymbol() {
    return symbol;
  }

  public String getName() {
    return name;
  }

  public double getShares() {
    return shares;
  }

  public String toString() {
    return shares + " shares of " + symbol + " (" + name + ")";
  }
}

Result


Related Tutorials