java8-1-practical usage example


Good evening, reader friends. Today is the Ching Ming Festival, a day to remember the martyrs, and a day to remember the heroes sacrificed during the epidemic.

To memorize, I will summarize some simple functions of java8 commonly used in the author's daily development here, similar to the code examples, so that you can quickly find and read through when you forget to use rules, which may be inspiring for you.

1. Common examples

Java8 has been around for a long time, and the biggest new features are: Lambada expressions, functional programming, and streaming. Here is a brief list of my commonly used:

When Java8 processes data, it is generally divided into an intermediate state and a terminal state. The intermediate state refers to operations like .map .filter; terminal operations refer to: collect, reduce, sorted, foreach, etc., terminal operations mean the last step .

1. Collection-.map

 Set<Long> couponIds = objects.stream()
                .map(ReceivedCoupon::getCouponId)
                .collect(Collectors.toSet());

2. Filtering-.filter


 List<ReceivedCouponDTO> notConsumedDTOs = receivedCouponDTOS.stream()
                .filter(e -> e.getCoupon() != null)
                .filter(ReceivedCouponDTO::notConsumed)
                .collect(toList());

The predicate notConsumed here is a custom method that returns boolean. Here, the method is passed as a first-class citizen.

3. Statute-.reduce


 BigDecimal totalAmountToReduce = notConsumedDTOs.stream()
                .map(ReceivedCouponDTO::getCoupon)
                .filter(coupon -> coupon.getType() == CouponTypeEnum.NOMINAL)
                .map(CouponDTO::getAmount)
                .reduce(BigDecimal.ZERO, (a, b) -> a.add(b));

The above code is to calculate the sum of the discount amount of a certain type of coupon

4. One of the terminal operations-.collect

Collectors.summingInt


 Integer imUnreadTotalCount = conversations.stream()
                .filter(e -> e != null)
                .filter(e -> e.getUnreadMessageCount() != null)
                .collect(Collectors.summingInt(ConversationInfo::getUnreadMessageCount));

Collectors.toMap

List<CouponDTO> couponDTOS = couponService.getByIds(couponIds);
        Map<Long, CouponDTO> couponDTOMap = Maps.newHashMap();
        if (CollectionsUtils.isNotEmpty(couponDTOS)) {
            couponDTOMap = couponDTOS.stream()
                    .collect(Collectors.toMap(CouponDTO::getId, couponDTO -> couponDTO));
        }

The system provides us with many useful Collectors by default, eg: summingInt, summingLong, summingDouble can be used directly here

Beyond the first time, there are many many functions: grouping, sorting, flatMap, etc., encountered perfect.

Published 181 original articles · praised 66 · 200,000 views

Guess you like

Origin blog.csdn.net/meiceatcsdn/article/details/105319771