Java8 functional interfaces and lambda expression practices

Source: Internet
Author: User

Recently re-learned and learned the functional interface of Java8 and lambda expression, found that the previous written code is mostly pseudo-function expression, so re-refining this part of the code, for reference only, if there is a better way, welcome comments in the comment area.

1. Calculate the total amount of the order

The total amount of the order is generally in the background loop overlay the amount of each purchased item has been acquired, usually in the following way

BigDecimal TotalAmount = new BigDecimal (0);
For (venditionproduct venditionproduct: venditionvo.getvenditionproductlist ()) { TotalAmount = Totalamount.add (Venditionproduct.getprice ()); }

Use lambda in the following way

        BigDecimal totalprice = Venditionvo.getvenditionproductlist (). Stream (). Map (Venditionproduct::getprice). Reduce (Bigdecimal::add). OrElse (Bigdecimal.one);

2. Cyclic collection assembly New class

The scenario is to update the field, and an update method, Updatenotnull, will appear below, which is a generic method that only updates properties that are not null for the field. Because only the price and Sellamount properties of the product are allowed in venditionproduct, it is not possible to directly update the collection that is passed by the front end directly, and the two properties need to be extracted to reassemble into the new class.

The procedure for comparing low is as follows (pseudo-function expression)

        Venditionproductlist.foreach (venditionproduct, {            venditionproduct newvenditionproduct = new Venditionproduct ();            Newvenditionproduct.setid (Venditionproduct.getid ());            Newvenditionproduct.setsellamount (Venditionproduct.getsellamount ());            Newvenditionproduct.setprice (Venditionproduct.getprice ());            Updatenotnull (newvenditionproduct);        });

The following is a true-function expression

Venditionproductlist.stream (). Map (Venditionproduct                Venditionproduct.build (Venditionproduct.getid (), Venditionproduct.getsellamount (), Venditionproduct.getprice ()))                . ForEach (This::updatenotnull);

3. Applications in enumerations

We have the following enumeration classes

  public enum Recordtypeenum {        /**         * 0 for manual warehousing  1 production Warehousing  2 manual out of the library   4 returns         in storage *        /manual_store (0),        Produce_store (1),        Manual_out (2),        vendition_out (3),        refund_in (4),;        private final int type;        Recordtypeenum (int type) {            this.type = type;        }    }

The scenario you are encountering may be that you want to find the corresponding enumeration value by type

The usual way is

public static recordtypeenum getrecordtypeenum (int type) {for        (recordtypeenum typeenum:                Recordtypeenum.values ()) {            if (typeenum.gettype () = = type) {                return typeenum;            }        }        return null;     }

Java8, we can do this like this.

public static recordtypeenum getRecordTypeEnum1 (int type) {        return Arrays.stream (Recordtypeenum.values ()).  Filter(Recordtypeenum-recordtypeenum.gettype () = = type). FindFirst (). OrElse (null);    }

And we might need to get the corresponding array

Public string[] Getenumstringarray () {        return Arrays.stream (Recordtypeenum.values ()). Map (Enum::name). ToArray ( string[]::new);    }

4. Writing a line of lambda syntax helps to improve the robustness of your code (the focus here is not on the use of lambda, but I think it's worth recording)

The business scenario is to increase the production schedule (plan), a schedule can have multiple products, a product needs one or more ingredients, so the relationship is a pair of many, the following look at my first write code (pseudo-function expression)

Focus on the last approach, the initial implementation is this

  

Here are two questions, one is that a short lambda expression can improve code readability, which is one of the important benefits of functional programming, which is completely overlooked, and the second is that planproduct (products) and planmaterial (raw materials) are linked together, In other words, the operation of adding raw materials should be encapsulated in the operation of adding products, the revised code is as follows

The reason for the record here is that while the lambda expression is streamlined into a single line of code, it is necessary to constantly adjust the structure of the code to move toward a more stable and robust direction, the original code logic, although the process is understandable, but ugly and long, as too many tasks.

5. Conversion from a set of known types to a collection of another type

The approximate logic is to obtain the raw material associated with the production product (including specifications), which is actually required to convert to list<planmaterial> according to List<productmaterail>

  

The practice here is to make the same mistake as above, the following adjustment

  

Java8 functional interfaces and lambda expression practices

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.