Iterating Over Collections - Java Lambda Stream

Java examples for Lambda Stream:Stream

Introduction

Generate a stream on any type that extends or implements java.util.Collection.

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", 5010.0));
    myStocks.add(new Stock("AAPL", "Apple", 2010.0));
    myStocks.add(new Stock("GOOG", "Google", 1100.0));
    myStocks.add(new Stock("IBM", "IBM", 510.0));
    myStocks.add(new Stock("MCD", "McDonalds", 3010.0));
    myStocks.stream().forEach(s -> System.out.println(s.getName()));

    boolean allGt = myStocks.stream().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.stream().filter(s -> s.getShares() > 100.0)
        .forEach(s -> System.out.println(s.getName()));

    System.out.println("sorted by shares:");
    Comparator<Stock> byShares = Comparator.comparing(Stock::getShares);
    Stream<Stock> sortedByShares = myStocks.stream().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.stream().findFirst();
    System.out.println("First Stock: " + maybe.get().getName());

    List<Stock> newStocks = new ArrayList<>();
    Optional<Stock> maybeNot = newStocks.stream().findFirst();
    Consumer<Stock> myConsumer = (s) -> {
      System.out.println("First Stock (Optional): " + s.getName());
    };//from ww  w .  j  a  v a2  s .  c o  m
    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