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-05 01:06:21.000000000 +0800
+++ new/src/share/sample/stream/Subset.java 2014-02-05 01:06:20.538506500 +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-05 01:06:24.000000000 +0800
+++ new/src/share/sample/stream/Tabulate.java 2014-02-05 01:06:23.161656500 +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-05 01:06:26.000000000 +0800
+++ new/src/share/sample/stream/data/Customer.java 2014-02-05 01:06:25.763805300 +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-05 01:06:29.000000000 +0800
+++ new/src/share/sample/stream/data/DataUtilities.java 2014-02-05 01:06:28.314951200 +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-05 01:06:31.000000000 +0800
+++ new/src/share/sample/stream/data/Order.java 2014-02-05 01:06:30.814094200 +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-05 01:06:34.000000000 +0800
+++ new/src/share/sample/stream/data/Product.java 2014-02-05 01:06:33.419243200 +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-05 01:06:36.000000000 +0800
+++ new/src/share/sample/stream/data/Vendor.java 2014-02-05 01:06:35.989390200 +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-05 01:06:39.000000000 +0800
+++ new/src/share/sample/stream/parallel/Fibonacci.java 2014-02-05 01:06:38.631541300 +0800
@@ -0,0 +1,132 @@
+/*
+ * 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.stream.IntStream;
+
+/**
+ * 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 {
+ /**
+ * A base matrix that will be used to calculate Fibonacci sequence.
+ */
+ private final static BigInteger[][] BASE
+ = new BigInteger[][]{
+ {BigInteger.ONE, BigInteger.ONE},
+ {BigInteger.ONE, BigInteger.ZERO}
+ } ;
+
+ /**
+ * @param args argument to run program
+ */
+ public static void main(String[] args) {
+ try {
+ if (args.length != 1) {
+ throw new Exception("Only allow one argument");
+ }
+ int position = Integer.parseInt(args[0]);
+ if (position < 0) {
+ throw new Exception("Postiion must be a positive integer");
+ }
+ System.out.printf("The %dth fibonacci number is %s\n" , position,
+ (position != 1 && position != 2) ?
+ power(BASE, position)[0][1].toString() : "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 BigInteger[][] times(BigInteger[][] matrix1,
+ BigInteger[][] matrix2) {
+ //Initialize all elements to zero
+ assert(matrix1.length == matrix2[0].length);
+ BigInteger[][] result = IntStream.range(0, matrix1.length).
+ mapToObj(i -> IntStream.range(0, matrix2[0].length).
+ mapToObj(v -> BigInteger.ZERO).toArray(BigInteger[]::new)).
+ toArray(BigInteger[][]::new);
+
+ 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] = result[row][col].
+ add(matrix1[row][col1].
+ multiply(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 BigInteger[][] power(BigInteger[][] matrix, int n) {
+ return IntStream.range(0, n).
+ mapToObj(i -> matrix).
+ parallel().
+ 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 positive integer");
+ }
+}
--- /dev/null 2014-02-05 01:06:41.000000000 +0800
+++ new/src/share/sample/stream/parallel/ImageTransform.java 2014-02-05 01:06:41.064680500 +0800
@@ -0,0 +1,231 @@
+/*
+ * 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.geom.AffineTransform;
+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;
+
+/**
+ * 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 "-zi":
+ 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("rotate")) {
+ int perimeter = (int)Math.sqrt(
+ newWidth * newWidth + newHeight * newHeight);
+ newWidth = perimeter;
+ newHeight = perimeter;
+ }
+ BufferedImage out = new BufferedImage(newWidth, newHeight, TYPE_INT_RGB);
+ switch (command) {
+ case "shift":
+ shift(in, out, yes, oprand);
+ break;
+ case "rotate":
+ rotate(in, out, yes, oprand);
+ break;
+ case "zoom":
+ zoom(in, out, oprand);
+ 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 oldCenterX = width / 2;
+ int oldCenterY = height / 2;
+ int centerXDelta = (int)out.getWidth() / 2 - oldCenterX;
+ int centerYDelta = (int)out.getHeight() / 2 - oldCenterY;
+ double rotateV = clockwise ? angle : -angle;
+ IntStream.range(0, width).parallel().forEach(x -> {
+ double[] columns = IntStream.range(0, height).flatMap(
+ i -> IntStream.of(x, i)).mapToDouble(i -> i).toArray();
+ AffineTransform.getRotateInstance(Math.toRadians(rotateV),
+ oldCenterX, oldCenterY).transform(columns, 0, columns, 0, height);
+ IntStream.range(0, height).forEach(y -> out.setRGB(
+ (int)columns[2 * y] + centerXDelta,
+ (int)columns[2 *y + 1] + centerYDelta,
+ 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).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 percentage percentage that image will zoom in/out.
+ */
+ public static void zoom(BufferedImage in, BufferedImage out, int percentage) {
+ int width = (int) out.getWidth();
+ int height = (int) out.getHeight();
+ double magnitude = percentage / 100.0;
+ IntStream.range(0, width).parallel().forEach(x -> {
+ IntStream.range(0, height).forEach(y -> {
+ int oldX = (int) (x / magnitude);
+ int oldY = (int) (y / magnitude);
+ 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).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|-rr angle|-lr angle|-zi percentage|-zo precentage|-iv] "
+ + "-i InputFile -o OutputFile");
+ }
+}
--- /dev/null 2014-02-05 01:06:44.000000000 +0800
+++ new/src/share/sample/stream/parallel/MonteCarloPI.java 2014-02-05 01:06:43.998848300 +0800
@@ -0,0 +1,86 @@
+/*
+ * 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;
+ }
+}
--- /dev/null 2014-02-05 01:06:47.000000000 +0800
+++ new/src/share/sample/stream/parallel/ProbablePrimeNumber.java 2014-02-05 01:06:46.233976200 +0800
@@ -0,0 +1,97 @@
+/*
+ * 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.concurrent.ThreadLocalRandom;
+import java.util.stream.IntStream;
+
+/**
+ * This demo shows how to use the parallel mode to find several number for given
+ * length prime number. The process easily use a parallel stream to generate
+ * a number of desired length probable prime number. Following with filter
+ * operation to make sure we will get desirable length prime numbers.
+ *
+ * @author tyan
+ */
+public class ProbablePrimeNumber {
+ /**
+ * 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 probable prime number that will be generated if it's set.
+ */
+ private static int DEFAULT_NUM = 1 << 10;
+
+ public static void main(String[] args) {
+ if (args.length != 1 && args.length != 2) {
+ usage();
+ return;
+ }
+ try {
+ int expectedLength = Integer.parseInt(args[0]);
+ int size = (args.length == 2) ?
+ Integer.parseInt(args[1]) :
+ DEFAULT_NUM;
+ IntStream.range(0, size).
+ parallel().
+ mapToObj(i ->
+ BigInteger.probablePrime(expectedLength * 10 / 3 -
+ ThreadLocalRandom.current().nextInt(3),
+ ThreadLocalRandom.current())).
+ filter(c -> c.toString().length() == expectedLength).
+ forEach(prime ->
+ System.out.println("Found a probable prime number :"
+ + prime));
+ } catch (NumberFormatException nfe) {
+ usage();
+ }
+ }
+
+ /**
+ * Usage of this program
+ */
+ public static void usage() {
+ System.out.println("Usage: java ProbablePrimeNumber lentgh [size]");
+ System.out.println("size is a positive integer");
+ }
+}