Java 8 集合的 Streams 使用示例

  Streams 是 Java 8 集合的新特性

  import java.util.ArrayList;

  import java.util.List;

  import java.util.stream.Stream;

  public class StreamDemo{

  public static void main(String args[]) {

  // Initialization of Collection

  List orderBook = new ArrayList<>();

  Order buyGoogle = new Order("GOOG.NS", 300, 900.30, Order.Side.BUY);

  Order sellGoogle = new Order("GOOG.NS", 600, 890.30, Order.Side.SELL);

  Order buyApple = new Order("APPL.NS", 400, 552, Order.Side.BUY);

  Order sellApple = new Order("APPL.NS", 200, 550, Order.Side.SELL);

  Order buyGS = new Order("GS.NS", 300, 130, Order.Side.BUY);

  orderBook.add(buyGoogle);

  orderBook.add(sellGoogle);

  orderBook.add(buyApple);

  orderBook.add(sellApple);

  orderBook.add(buyGS);

  // Java 8 Streams Example 1 : Filtering Collection elements

  // Filtering buy and sell order using filter() method of java.util.Stream class

  Stream stream = orderBook.stream();

  Stream buyOrders = stream.filter((Order o) -> o.side().equals(Order.Side.BUY));

  System.out.println("No of Buy Order Placed :" + buyOrders.count());

  Stream sellOrders = orderBook.stream().filter((Order o) -> o.side() == Order.Side.SELL);

  System.out.println("No of Sell Order Placed : " + sellOrders.count());

  // Java 8 Streams Example 2 : Reduce or Fold operation

  // Calculating total value of all orders

  double value = orderBook.stream().mapToDouble((Order o) -> o.price()).sum();

  System.out.println("Total value of all orders : " + value);

  long quantity = orderBook.stream().mapToLong((Order o) -> o.quantity()).sum();

  System.out.println("Total quantity of all orders : " + quantity);

  }

  }

  class Order {

  enum Side {

  BUY, SELL;

  }

  private final String symbol;

  private final int quantity;

  private double price;

  private final Side side;

  public Order(String symbol, int quantity, double price, Side side) {

  this.symbol = symbol;

  this.quantity = quantity;

  this.price = price;

  this.side = side;

  }

  public double price() {

  return price;

  }

  public void price(double price) {

  this.price = price;

  }

  public String symbol() {

  return symbol;

  }

  public int quantity() {

  return quantity;

  }

  public Side side() {

  return side;

  }

  }

  复制代码

  No of Buy Order Placed :3

  No of Sell Order Placed : 2

  Total value of all orders : 3022.6

  Total quantity of all orders : 1800


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值