customersToBigOrder = customers.stream().
+ //grouping customer to a Map which key is customer, value is
+ //total order price
+ collect(toConcurrentMap(Function.identity(),
+ orderTotal));
+ customersToBigOrder.forEach((customer, totalAmount) -> {
+ //Remove all customer whose total order amount is not greater than
+ //bigValue
+ if (totalAmount <= bigValue) {
+ customersToBigOrder.remove(customer);
+ }
+ });
+ return customersToBigOrder;
+ }
+}
--- /dev/null 2014-02-02 21:38:47.000000000 +0800
+++ new/src/share/sample/stream/Subset.java 2014-02-02 21:38:47.000000000 +0800
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+package stream;
+
+import stream.data.Customer;
+import stream.data.Order;
+import java.util.Comparator;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * A demo shows how does Stream's subset works. This demo provides two methods
+ * which is using substream method on Stream to get subset of the elements. Note
+ * we can use substream on sorted stream to get top number elements, but we
+ * can't guarantee the element order if stream is not sorted.
+ *
+ * @author hyan
+ */
+public class Subset extends DemoHelper {
+
+ /**
+ * Returns a List that contains numbers order which customer is from state,
+ * also execute action on every returned order element. The number must be a
+ * non-negative digit.
+ *
+ *
+ * @param number integer how many orders are expected to be returned
+ * @param state state that customer of order belong to
+ * @return a list contains top number customers that sorted by comp
+ */
+ public static List firstNOrdersFromState(int number,
+ String state) {
+ return customers.stream().
+ //only take customers from a particular state
+ filter(c -> state.equals(c.getRegion())).
+ //get orders of those customers
+ flatMap(c -> c.getOrders().stream()).
+ //get first number of orders
+ limit(number).
+ //collect to a list
+ collect(Collectors.toList());
+ }
+
+ /**
+ * Returns a List that contains numbers customer sorted by comp, also
+ * execute action on every returned customer element. The number must be a
+ * non-negative digit.
+ *
+ *
+ * @param number integer how many customers are expected to be returned
+ * @param comp Comparator to compare customer
+ * @return a list contains top number customers that sorted by comp
+ */
+ public static List topNCustomer(int number,
+ Comparator comp) {
+ //We keep result in topN, then we can test it
+ return customers.stream()
+. //sort customers by comp
+ sorted(comp).
+ //get first number of orders
+ limit(number).
+ //collect to a list
+ collect(Collectors.toList());
+ }
+}
--- /dev/null 2014-02-02 21:38:48.000000000 +0800
+++ new/src/share/sample/stream/Tabulate.java 2014-02-02 21:38:48.000000000 +0800
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+package stream;
+
+import stream.data.Customer;
+import stream.data.Vendor;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import static java.util.stream.Collectors.*;
+import java.util.stream.Stream;
+
+/**
+ * A demo shows how does Stream's flatMap works. Demo shows tabulate stream
+ * element to single element stream or empty stream
+ *
+ * @author tyan
+ */
+public class Tabulate extends DemoHelper {
+ /**
+ * Join vendor and customer that in same country. note not all vendor
+ * has customer
+ * @return a list of customer-vendor pair which in same country
+ */
+ public static Map> sameCountryCustomerAndVendors() {
+ Map> countryToVendors = vendors.stream().
+ // group vendors by their country
+ collect(groupingBy(Vendor::getCountry));
+ //Find customer in countryToVendors with key as customer's country
+ Function> vendorsInSameCustomerCountry
+ = customer-> countryToVendors.getOrDefault(
+ customer.getCountry(), new ArrayList<>());
+ //Map customer to vendor who are same country as customer's
+ return customers.stream().
+ filter(c -> countryToVendors.containsKey(c.getCountry())).
+ collect(toMap(Function.identity(), vendorsInSameCustomerCountry));
+ }
+
+ /**
+ * flatMap can generate empty stream, sometimes it's helpful for ruling
+ * out data
+ * @return a string set who is either customer and vendor both.
+ */
+ public static Set bothCustomerAndVendor() {
+ Set vendorsName = vendors.stream().
+ map(Vendor::getVendorName).
+ collect(toSet());
+ return customers.stream().
+ //map customer to its name
+ map(Customer::getCompanyName).
+ //query vendor set with customer's name, if exist, create
+ //a stream with single element customer name, if doesn't, create
+ //an empty stream
+ flatMap(c -> vendorsName.contains(c)
+ ? Stream.of(c) : Stream.empty()).
+ //convert all match name into a set
+ collect(Collectors.toSet());
+ }
+}
--- /dev/null 2014-02-02 21:38:49.000000000 +0800
+++ new/src/share/sample/stream/data/Customer.java 2014-02-02 21:38:49.000000000 +0800
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+package stream.data;
+
+import java.util.ArrayList;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlElementWrapper;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlType;
+
+/**
+ * Customer meta data class, one customer could have zero to multiple orders
+ *
+ * @author tyan
+ */
+public @XmlRootElement(name = "customer")
+@XmlType(propOrder = {"customerID", "companyName", "address", "city", "region",
+ "postalcode", "country", "phone", "fax", "orders"})
+class Customer {
+
+ private String customerID;
+ private String companyName;
+ private String address;
+ private String city;
+ private String region;
+ private String postalcode;
+ private String country;
+ private String phone;
+ private String fax;
+
+ @XmlElementWrapper(name = "orders")
+ @XmlElement(name = "order")
+ private ArrayList orders;
+
+ /**
+ * @return the customerID
+ */
+ @XmlElement(name = "id")
+ public String getCustomerID() {
+ return customerID;
+ }
+
+ /**
+ * @param customerID the customerID to set
+ */
+ public void setCustomerID(String customerID) {
+ this.customerID = customerID;
+ }
+
+ /**
+ * @return the companyName
+ */
+ @XmlElement(name = "name")
+ public String getCompanyName() {
+ return companyName;
+ }
+
+ /**
+ * @param companyName the companyName to set
+ */
+ public void setCompanyName(String companyName) {
+ this.companyName = companyName;
+ }
+
+ /**
+ * @return the address
+ */
+ public String getAddress() {
+ return address;
+ }
+
+ /**
+ * @param address the address to set
+ */
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+ /**
+ * @return the city
+ */
+ public String getCity() {
+ return city;
+ }
+
+ /**
+ * @param city the city to set
+ */
+ public void setCity(String city) {
+ this.city = city;
+ }
+
+ /**
+ * @return the region
+ */
+ public String getRegion() {
+ return region;
+ }
+
+ /**
+ * @param region the region to set
+ */
+ public void setRegion(String region) {
+ this.region = region;
+ }
+
+ /**
+ * @return the postalcode
+ */
+ public String getPostalcode() {
+ return postalcode;
+ }
+
+ /**
+ * @param postalcode the postalcode to set
+ */
+ public void setPostalcode(String postalcode) {
+ this.postalcode = postalcode;
+ }
+
+ /**
+ * @return the country
+ */
+ public String getCountry() {
+ return country;
+ }
+
+ /**
+ * @param country the country to set
+ */
+ public void setCountry(String country) {
+ this.country = country;
+ }
+
+ /**
+ * @return the phone
+ */
+ public String getPhone() {
+ return phone;
+ }
+
+ /**
+ * @param phone the phone to set
+ */
+ public void setPhone(String phone) {
+ this.phone = phone;
+ }
+
+ /**
+ * @return the fax
+ */
+ public String getFax() {
+ return fax;
+ }
+
+ /**
+ * @param fax the fax to set
+ */
+ public void setFax(String fax) {
+ this.fax = fax;
+ }
+
+ /**
+ * @return the orders
+ */
+ public final ArrayList getOrders() {
+ return orders;
+ }
+}
--- /dev/null 2014-02-02 21:38:50.000000000 +0800
+++ new/src/share/sample/stream/data/DataUtilities.java 2014-02-02 21:38:50.000000000 +0800
@@ -0,0 +1,240 @@
+/*
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+package stream.data;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * DataUtilities is a singleton helper class that creates test data. This class
+ * uses jaxws API to read xml into java object, which includes 3 list of data 1.
+ * Customers 2. Products 3. Vendors Note in this demo here we don't use stream
+ * API to change data, if we use stream API to populate source data, we should
+ * be aware this is not free and not thread-safe.
+ */
+interface XMLList {
+
+ public List getList();
+}
+
+/**
+ * class for PRODUCTS_XML's root
+ */
+@XmlRootElement(name = "products")
+class Products implements XMLList {
+
+ /**
+ * node products only contains product list
+ */
+ @XmlElement(name = "product")
+ private ArrayList products;
+
+ /**
+ * product list
+ */
+ @Override
+ public List getList() {
+ return products;
+ }
+}
+
+/**
+ * class for VENDORS_XML's root
+ */
+@XmlRootElement(name = "vendors")
+class Vendors implements XMLList {
+
+ /**
+ * node Vendors only contains vendor list
+ */
+
+ @Override
+ public List getList() {
+ return vendors;
+ }
+
+ /**
+ * vendor list
+ */
+ @XmlElement(name = "vendor")
+ private ArrayList vendors;
+}
+
+/**
+ * class for CUSTOMERS_XML's root
+ */
+@XmlRootElement(name = "customers")
+class Customers implements XMLList {
+
+ /**
+ * node customers only contains customer list
+ */
+ @Override
+ public List getList() {
+ return customers;
+ }
+
+ /**
+ * customer list
+ */
+ @XmlElement(name = "customer")
+ private ArrayList customers;
+}
+
+public class DataUtilities {
+
+ /**
+ * xml file name for Customers object
+ */
+
+ private final static String CUSTOMERS_XML = "Customers.xml";
+
+ /**
+ * xml file name for Products object
+ */
+ private final static String PRODUCTS_XML = "Products.xml";
+
+ /**
+ * xml file name for Products object
+ */
+ private final static String VENDORS_XML = "Vendors.xml";
+
+ /**
+ * Lazy initiate static inner class for
+ */
+ private static class UtilitiesHolder {
+
+ static DataUtilities instance = new DataUtilities();
+ }
+
+ /**
+ * private constructor is needed for singleton
+ */
+ private DataUtilities() {
+ }
+
+ //products
+ private List productList;
+
+ //customer
+ private List customerList;
+
+ //vendors
+ private List vendorList;
+
+ /**
+ * Lazy initial to get product list
+ *
+ * @return initiated product list
+ */
+ public List getProductList() {
+ if (productList == null) {
+ createLists();
+ }
+ return productList;
+ }
+
+ /**
+ * Lazy initial to get customer list
+ *
+ * @return initiated customer list
+ */
+ public List getCustomerList() {
+ if (customerList == null) {
+ createLists();
+ }
+ return customerList;
+ }
+
+ /**
+ * Lazy initial to get vendor list
+ *
+ * @return initiated vendor list
+ */
+ public List getVendorList() {
+ if (vendorList == null) {
+ createLists();
+ }
+ return vendorList;
+ }
+
+ /**
+ * convert xml files to java objects
+ */
+ private void createLists() {
+ customerList = xmlToObject(Customers.class, CUSTOMERS_XML);
+ productList = xmlToObject(Products.class, PRODUCTS_XML);
+ vendorList = xmlToObject(Vendors.class, VENDORS_XML);
+ }
+
+ /**
+ * Convert a xml file to instance of class by given file name
+ *
+ * @param clazz to be converted java object's class
+ * @param file xml file name
+ * @return a list of object that xml's root contains
+ */
+ private > List xmlToObject(Class clazz,
+ String file) {
+ try {
+ JAXBContext context = JAXBContext.newInstance(clazz);
+ Unmarshaller um = context.createUnmarshaller();
+ @SuppressWarnings("unchecked")
+ V cs = (V) um.unmarshal(new File(file));
+ return cs.getList();
+ } catch (JAXBException ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ /**
+ * static factory method for singleton
+ *
+ * @return a DataUtitlities signgleton instance
+ */
+ public static DataUtilities getUtilities() {
+ return UtilitiesHolder.instance;
+ }
+}
--- /dev/null 2014-02-02 21:38:51.000000000 +0800
+++ new/src/share/sample/stream/data/Order.java 2014-02-02 21:38:51.000000000 +0800
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+package stream.data;
+
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * Order meta data class
+ *
+ * @author tyan
+ */
+@XmlRootElement(name = "order")
+public class Order {
+
+ /**
+ * @return id of order.
+ */
+ @XmlElement(name = "id")
+ public int getOrderId() {
+ return orderId;
+ }
+
+ /**
+ * Set orderId
+ *
+ * @param orderId order's id
+ */
+ public void setOrderId(int orderId) {
+ this.orderId = orderId;
+ }
+
+ /**
+ * @return string of order's date
+ */
+ public String getOrderdate() {
+ return dtf.format(orderdate);
+ }
+
+ /**
+ * @return order date
+ */
+ public LocalDateTime getLocalOrderdate() {
+ return orderdate;
+ }
+
+ /**
+ * Set orderdate
+ *
+ * @param orderdate order date
+ */
+ public void setOrderdate(String orderdate) {
+ this.orderdate = LocalDateTime.parse(orderdate, dtf);
+ }
+
+ /**
+ * @return total number of order
+ */
+ public double getTotal() {
+ return total;
+ }
+
+ /**
+ * Set total number
+ *
+ * @param total total number of this odder
+ */
+ public void setTotal(double total) {
+ this.total = total;
+ }
+
+ /**
+ * Id of order.
+ */
+ private int orderId;
+
+ /**
+ * order date.
+ */
+ private LocalDateTime orderdate;
+
+ /**
+ * Total number of order.
+ */
+ private double total;
+
+ /**
+ * Formatter for convert orderdate and String
+ */
+ private final DateTimeFormatter dtf
+ = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+}
--- /dev/null 2014-02-02 21:38:52.000000000 +0800
+++ new/src/share/sample/stream/data/Product.java 2014-02-02 21:38:52.000000000 +0800
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+package stream.data;
+
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlType;
+
+/**
+ * Product meta data class
+ *
+ * @author tyan
+ */
+@XmlRootElement(name = "product")
+@XmlType(propOrder = {"productID", "productName", "category", "unitPrice",
+ "unitsInStock"})
+public class Product {
+
+ private int productID;
+ private String productName;
+ private String category;
+ private double unitPrice;
+ private int unitsInStock;
+
+ /**
+ * @return the productID
+ */
+ public int getProductID() {
+ return productID;
+ }
+
+ /**
+ * @param productID the productID to set
+ */
+ public void setProductID(int productID) {
+ this.productID = productID;
+ }
+
+ /**
+ * @return the productName
+ */
+ public String getProductName() {
+ return productName;
+ }
+
+ /**
+ * @param productName the productName to set
+ */
+ public void setProductName(String productName) {
+ this.productName = productName;
+ }
+
+ /**
+ * @return the category
+ */
+ public String getCategory() {
+ return category;
+ }
+
+ /**
+ * @param category the category to set
+ */
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ /**
+ * @return the unitPrice
+ */
+ public double getUnitPrice() {
+ return unitPrice;
+ }
+
+ /**
+ * @param unitPrice the unitPrice to set
+ */
+ public void setUnitPrice(double unitPrice) {
+ this.unitPrice = unitPrice;
+ }
+
+ /**
+ * @return the unitsInStock
+ */
+ public int getUnitsInStock() {
+ return unitsInStock;
+ }
+
+ /**
+ * @param unitsInStock the unitsInStock to set
+ */
+ public void setUnitsInStock(int unitsInStock) {
+ this.unitsInStock = unitsInStock;
+ }
+}
--- /dev/null 2014-02-02 21:38:53.000000000 +0800
+++ new/src/share/sample/stream/data/Vendor.java 2014-02-02 21:38:53.000000000 +0800
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+package stream.data;
+
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlType;
+
+/**
+ * Vendor meta data class, it's possible some vendor is customer as well.
+ *
+ * @author tyan
+ */
+public @XmlRootElement(name = "vendor")
+@XmlType(propOrder = {"vendorName", "address", "city", "country"})
+class Vendor {
+
+ private String vendorName;
+ private String address;
+ private String city;
+ private String country;
+
+ /**
+ * @return the vendorName
+ */
+ public String getVendorName() {
+ return vendorName;
+ }
+
+ /**
+ * @param vendorName the vendorName to set
+ */
+ public void setVendorName(String vendorName) {
+ this.vendorName = vendorName;
+ }
+
+ /**
+ * @return the address
+ */
+ public String getAddress() {
+ return address;
+ }
+
+ /**
+ * @param address the address to set
+ */
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+ /**
+ * @return the city
+ */
+ public String getCity() {
+ return city;
+ }
+
+ /**
+ * @param city the city to set
+ */
+ public void setCity(String city) {
+ this.city = city;
+ }
+
+ /**
+ * @return the country
+ */
+ public String getCountry() {
+ return country;
+ }
+
+ /**
+ * @param country the country to set
+ */
+ public void setCountry(String country) {
+ this.country = country;
+ }
+}
--- /dev/null 2014-02-02 21:38:54.000000000 +0800
+++ new/src/share/sample/stream/parallel/Fibonacci.java 2014-02-02 21:38:53.000000000 +0800
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+package stream.parallel;
+
+import java.util.stream.Stream;
+
+/**
+ * This demo shows how to use the parallel calculation to calculate Fibonacci
+ * sequence. This is a 2-dimensional system of linear difference equations that
+ * describes the Fibonacci sequence.
+ *
+ * @author tyan
+ */
+public class Fibonacci {
+ /**
+ * First Fibonacci number.
+ */
+ private final static long FIBONACCI_1 = 1;
+
+ /**
+ * Second Fibonacci number.
+ */
+ private final static long FIBONACCI_2 = 1;
+
+ /**
+ * A base matrix that will be used to calculate Fibonacci sequence.
+ */
+ private final static long[][] BASE
+ = new long[][]{
+ {FIBONACCI_2, FIBONACCI_1},
+ {FIBONACCI_1, 0}
+ } ;
+
+ /**
+ * @param args argument to run program
+ */
+ public static void main(String[] args) {
+ try {
+ if (args.length != 1) {
+ throw new Exception("Only accept one argument");
+ }
+ int position = Integer.parseInt(args[0]);
+ if (position < 3) {
+ throw new Exception("Postiion must be greater than 3");
+ }
+ System.out.printf("The %dth fibonacci number is %d\n" , position,
+ power(BASE, position)[0][1]);
+ } catch (Exception nfe) {
+ usage();
+ }
+ }
+
+ /**
+ * Matrix binaries operation multiplication.
+ * @param matrix1 matrix to be multiplied.
+ * @param matrix2 matrix to multiply.
+ * @return A new generated matrix which has same number of rows as matrix1
+ * and same number of columns as matrix2.
+ */
+ private static long[][] times(long[][] matrix1, long[][] matrix2) {
+ long[][] result = new long[2][2];
+ for(int row = 0; row < matrix1.length; row++) {
+ for(int col =0; col < matrix2[row].length; col++) {
+ for(int col1 =0; col1 < matrix1[row].length; col1++) {
+ result[row][col] += matrix1[row][col1] * matrix2[col1][col];
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Power operation to matrix. Requirement for power operation is matrix must
+ * have same number row and column.
+ * @param matrix base
+ * @param n the exponent
+ * @return the value of the first argument raised to the power of the second
+ * argument.
+ */
+ private static long[][] power(long[][] matrix, int n) {
+ return Stream.generate(() -> matrix).
+ limit(n).
+ reduce(Fibonacci::times).
+ get();
+ }
+
+ /**
+ * Usage of this program
+ */
+ public static void usage() {
+ System.out.println("Usage: java Fibonacci Position");
+ System.out.println("Postiion must be a integer greater than 3");
+ }
+}
--- /dev/null 2014-02-02 21:38:55.000000000 +0800
+++ new/src/share/sample/stream/parallel/ImageTransform.java 2014-02-02 21:38:54.000000000 +0800
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+package stream.parallel;
+
+import java.awt.image.BufferedImage;
+import static java.awt.image.BufferedImage.TYPE_INT_RGB;
+import java.io.File;
+import java.util.stream.IntStream;
+import javax.imageio.ImageIO;
+import static stream.parallel.RandomPrimeNumber.usage;
+
+/**
+ * This demo shows parallel geometrical transformations of images.The operations
+ * of image include rotation, shift, scale, inversion.
+ *
+ * @author tyan
+ */
+public class ImageTransform {
+
+ public static void main(String[] args) {
+ try {
+ if (args.length < 5) {
+ usage();
+ return;
+ }
+ int argPos = 0;
+ int oprand = 0;
+ String command = "";
+ String inputFile = "", outputFile = "";
+ boolean yes = true;
+ while (argPos < args.length) {
+ switch (args[argPos++]) {
+ case "-ls":
+ case "-rs":
+ yes = args[argPos - 1].equals("-ls");
+ oprand = Integer.parseInt(args[argPos++]);
+ command = "shift";
+ break;
+ case "-cl":
+ case "-ccl":
+ yes = args[argPos - 1].equals("-cl");
+ oprand = Integer.parseInt(args[argPos++]);
+ command = "rotate";
+ break;
+ case "-zo":
+ oprand = Integer.parseInt(args[argPos++]);
+ command = "zoom";
+ break;
+ case "-iv":
+ command = "invert";
+ break;
+ case "-i":
+ inputFile = args[argPos++];
+ break;
+ case "-o":
+ outputFile = args[argPos++];
+ break;
+ default:
+ usage();
+ return;
+ }
+ }
+ if (inputFile.equals("") || outputFile.equals("")) {
+ throw new Exception("Input/Output file is needed");
+ }
+ File inFile = new File(inputFile);
+ File outFile = new File(outputFile);
+ BufferedImage in = ImageIO.read(inFile);
+ int newWidth = in.getWidth();
+ int newHeight = in.getHeight();
+ if (command.equals("zoom")) {
+ double magnitude = oprand / 100.0;
+ newWidth = (int) (newWidth * magnitude);
+ newHeight = (int) (newHeight * magnitude);
+ } else if (command.equals("rorate")) {
+ int max = Math.max(newWidth, newWidth);
+ newWidth = max;
+ newHeight = max;
+ }
+ BufferedImage out = new BufferedImage(newWidth, newHeight, TYPE_INT_RGB);
+ if(!command.equals("invert") && oprand <= 0) {
+ throw new Exception("Value must be a positive number");
+ }
+ switch (command) {
+ case "shift":
+ shift(in, out, yes, oprand);
+ break;
+ case "rotate":
+ rotate(in, out, yes, oprand);
+ break;
+ case "zoom":
+ zoom(in, out, oprand / 100.0);
+ break;
+ case "invert":
+ invert(in, out);
+ break;
+ }
+ ImageIO.write(out, "jpg", outFile);
+ } catch (Exception ex) {
+ usage();
+ }
+ }
+
+ /**
+ * Rotate an image as given angle.
+ * @param in input image
+ * @param out output image
+ * @param clockwise true clockwise
+ * false counter-clockwise
+ * @param angle angle that image will rotate
+ */
+ public static void rotate(BufferedImage in, BufferedImage out,
+ boolean clockwise, int angle) {
+ int width = (int) in.getWidth();
+ int height = (int) in.getHeight();
+ int centerX = width / 2;
+ int centerY = height / 2;
+ double rotateV = (clockwise ? 360 - angle : angle) / 180.0 * Math.PI;
+ IntStream.range(0, width).parallel().forEach(x -> {
+ IntStream.range(0, height).parallel().forEach(y -> {
+ int newX = (int) (centerX + (x - centerX) * Math.cos(rotateV)
+ + (y - centerY) * Math.sin(rotateV));
+ int newY = (int) (centerY + (x - centerX) * Math.sin(rotateV)
+ + (y - centerY) * Math.cos(rotateV));
+ if (newX >= 0 && newX < width && newY >= 0 && newY < height) {
+ out.setRGB(newX, newY, in.getRGB(x, y));
+ }
+ });
+ });
+ }
+
+ /**
+ * Shift an image horizontally.
+ * @param in input image
+ * @param out output image
+ * @param left true left shift
+ * false right shift
+ * @param length size that image shifts
+ */
+ public static void shift(BufferedImage in, BufferedImage out,
+ boolean left, int length) {
+ int width = (int) out.getWidth();
+ int height = (int) out.getHeight();
+ int leftShift = left ? length % width : width - length % width;
+ IntStream.range(0, width).parallel().forEach(x -> {
+ IntStream.range(0, height).parallel().forEach(y -> {
+ int newX = x >= leftShift ? x - leftShift : width + x - leftShift;
+ out.setRGB(newX, y, in.getRGB(x, y));
+ });
+ });
+ }
+
+ /**
+ * Zoom in/out an image.
+ * @param in input image
+ * @param out output image
+ * @param magnitude scale of original image.
+ */
+ public static void zoom(BufferedImage in, BufferedImage out,
+ double magnitude) {
+ int width = (int) out.getWidth();
+ int height = (int) out.getHeight();
+ IntStream.range(0, width).parallel().forEach(x -> {
+ IntStream.range(0, height).parallel().forEach(y -> {
+ int oldX = (int) (x / magnitude);
+ int oldY = (int) (y / magnitude);
+ if (oldX < in.getWidth() && oldY < in.getHeight()) {
+ out.setRGB(x, y, in.getRGB(oldX, oldY));
+ }
+ });
+ });
+ }
+
+ /**
+ * Invert color of an image.
+ * @param in input image
+ * @param out output image
+ */
+ public static void invert(BufferedImage in, BufferedImage out) {
+ int width = (int) out.getWidth();
+ int height = (int) out.getHeight();
+ IntStream.range(0, width).parallel().forEach(x -> {
+ IntStream.range(0, height).parallel().forEach(y -> {
+ out.setRGB(x, y, in.getRGB(x, y) ^ 0xffffff);
+ });
+ });
+ }
+
+ /**
+ * Usage of this program
+ */
+ public static void usage() {
+ System.out.println("Usage: java ImageTransform {-rs size|-ls size|"
+ + "-cl angle|-ccl angle|-zo percentage|-zo precentage|-iv} "
+ + "-i InputFile -o OutputFile");
+ }
+}
--- /dev/null 2014-02-02 21:38:56.000000000 +0800
+++ new/src/share/sample/stream/parallel/MonteCarloPI.java 2014-02-02 21:38:55.000000000 +0800
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+package stream.parallel;
+
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.stream.LongStream;
+
+/**
+ * This demo shows how to use the parallel mode and the Monte Carlo method to
+ * calculate the value of PI
+ *
+ * @author tyan
+ */
+public class MonteCarloPI {
+
+ public static void main(String[] args) {
+ System.out.println("This might take several minutes, "
+ + "depending on your system");
+ LongStream.iterate(10l, l -> 10 * l).
+ limit(10).
+ forEach(times -> {
+ System.out.printf(
+ "The value of PI is %1.14f after %,d times calculation\n",
+ pi(times), times);
+ });
+ }
+
+ /**
+ * Use the Monte Carlo method to calculate the value of PI. basic algorithm
+ * is: 1. Draw a square on the ground, then inscribe a circle within it. 2.
+ * Scatter some objects of uniform size (grains of rice or sand) over the
+ * square. 3. Count the total number of objects inside the circle and the
+ * total number of objects overall. 4. The ratio of the two total is an
+ * estimate of the ratio of the two areas, which is PI/4. Multiply the
+ * result by 4 to estimate PI.
+ *
+ * @param x how many times randomly selected a point
+ * @return value of π by x times calculation
+ */
+ private static double pi(long N) {
+ long M = LongStream.range(0, N).parallel().filter(sr -> {
+ // Random picked up point to check if it's in the circle.
+ double x = ThreadLocalRandom.current().nextDouble(-1, 1);
+ double y = ThreadLocalRandom.current().nextDouble(-1, 1);
+
+ return x * x + y * y < 1.0 * 1.0; // Not using
+ }).count();
+ return 4.0 * M / N;
+ }
+
+ /**
+ * Use ThreadLocalRandom to simulate that whether a point is inside the
+ * circle or outside the circle
+ *
+ * @return 1 randomly selected point is inside the circle 0 randomly
+ * selected point is outside the circle
+ */
+ private static long hit() {
+ ThreadLocalRandom lr = ThreadLocalRandom.current();
+ double x = lr.nextDouble(1.0);
+ double y = lr.nextDouble(1.0);
+ return Math.sqrt(y * y + x * x) <= 1.0 ? 1 : 0;
+ }
+}
--- /dev/null 2014-02-02 21:38:57.000000000 +0800
+++ new/src/share/sample/stream/parallel/RandomPrimeNumber.java 2014-02-02 21:38:56.000000000 +0800
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+package stream.parallel;
+
+import java.math.BigInteger;
+import java.util.Random;
+import java.util.stream.LongStream;
+
+/**
+ * This demo shows how to use the parallel mode to find several number of
+ * unknown length�prime number. The process easily use new Random.LongStream
+ * generates a desired length stream. Following with filter operation. Here
+ * input length is desirable long stream length instead of number of prime
+ * number.
+ *
+ * @author tyan
+ */
+public class RandomPrimeNumber {
+ /**
+ * By default we only calculate at most 64 numbers once..
+ */
+ private final static long RANGE_SIZE = 1 << 6;
+
+ /**
+ * Try to get length from command line. Use the length to create random long
+ * stream, that integer's digit is length.
+ *
+ * @param args This has to be a 1-element or 2-elements array, The first
+ * element must be a positive number, which equals to length of generated
+ * prime number stream. Second element is optional, it will be used as how
+ * many prime number that will be generated if it's set.
+ */
+ public static void main(String[] args) {
+ if (args.length != 1 && args.length != 2) {
+ usage();
+ return;
+ }
+ try {
+ int length = Integer.parseInt(args[0]);
+ if (length > 16) {
+ System.out.println("Can calculate maximun only l6 digits "
+ + "prime number");
+ return;
+ }
+ long numberOfPrime = RANGE_SIZE;
+ if (args.length == 2) {
+ numberOfPrime = Long.parseLong(args[1]);
+ }
+ long minNDigit = BigInteger.valueOf(10L).pow(length - 1).longValue();
+ long maxNDigit = BigInteger.valueOf(10L).pow(length).longValue();
+
+ new Random(System.currentTimeMillis()).
+ longs(numberOfPrime, minNDigit, maxNDigit).
+ filter(N -> isPrime(N)).
+ forEach(System.out::println);
+ } catch (NumberFormatException nfe) {
+ usage();
+ }
+ }
+
+ /**
+ * Decide if a BigInteger is a prime number
+ *
+ * @param integer a number
+ * @return true if integer is a prime number false if integer is not a prime
+ * number
+ */
+ private static boolean isPrime(long number) {
+ //This is a parall version that checks if a number is a prime number
+ return !LongStream.range(2L, Math.round(Math.sqrt(number))).parallel().
+ anyMatch(divisor -> number % divisor == 0);
+ }
+
+ /**
+ * Usage of this program
+ */
+ public static void usage() {
+ System.out.println("Usage: java RandomPrimeNumber lentgh[size]");
+ System.out.println("length is a positive integer not greater than 16");
+ System.out.println("size is a positive integer");
+ }
+}