JDK7发布两年多后,Java8终于来到了我们面前,我们对很多它的特性期待好久了。其中lambda表达式
是我们谈论最多的一项,但是这个特性还远不是现在的主流,Java8带来了新的stream实现类,实现了
Collections元素的并行处理。可以通过指定条件来过滤集合元素。如果集合是有序的,可以通过集合元素的属性
进行排序。也可以使用常用的功能编程函数,也就是map和reduce。stream类提供诸如mapToInt()、mapToLong()和
处理集合元素的map函数。在当前例子中,我们会列出使用java8 stream来处理集合元素。Stream类的使用也不只限于
Collections,也可以使用数组,生成函数,或者IO通道。大多数情况下,Java 8中的Stream管道包括一个source源,然后是0或者多个filter()
或者map(),最后是forEach()或者reduce()。
下面是Java8中使用Stream来处理集合的代码
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<Order> 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<Order> 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<Order> 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; } } Output: 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