The source code is for testing only and should not be used commercially. The source code comes from the Internet. If there is any infringement, please contact me to remove it.
Java8 Stream Api 中的peek操作

1. preface

I'mDetailed usage guide for the Java 8 Stream API It tells Java 8 Stream API in map operation and flatMap The difference in operation. Then a friend told me peek Operations can also implement the processing of elements. but you know map and peek Is the difference? map We have already talked about it in the beginning of the article. You can go and learn about it in detail. This article will focus on explaining it peek Operation.

2. peek

peek The operation receives a Consumer<T> Function. As the name suggests, the peek operation will follow Consumer<T> The logic provided by the function consumes every element in the flow, while potentially changing some attributes within the element.
Here we want to mention this Consumer<T> To understand what consumption is.

2.1 What is consumer?

package java.util.function;

import java.util.Objects;


@FunctionalInterface
public interface Consumer<T> {

    void accept(T t);

     //Nested accept , in the order of accept first, and then after.accpet in the parameter is executed
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
 }

Consumer<T> Is a functional interface. an abstract method void accept(T t) It means accepting a person T Parameter of type and consume it. In fact, the feeling that consumption gives me is "used up", and the natural return is void 。Usually "used up" T There are two ways:

  • The void method of T itself The more typical one is setter
  • Give T to the void method of other interfaces (classes) for processing For example, we often use printing an object System.out.println(T)

2.2 peek operation demonstration

 Stream<String> stream = Stream.of("hello", "felord.cn");
   stream.peek(System.out::println);

If you test the code given above, you will find that it will not follow logic at all. Why is this? This is because the life cycle of a stream has three phases:

  • Start the generation phase.
  • Intermediate operations retrieve and process elements one by one. It's optional.All intermediate operations are inert, so no operation will have any impact before the flow flows in the pipe.
  • Terminal operations. usually divided into the final consumerforeach and the like) and summarizedcollect) Two categories. Another important point is that the terminal operation initiates the flow of flow in the pipeline.

So it should be changed to the following:

 Stream<String> stream = Stream.of("hello", "felord.cn");
  List<String> strs= stream.peek(System.out::println).collect(Collectors.toLIst());

For example, in the picture below, we added a box to the sphere:

3. peek VS map

peek Operations are generally used when you do not want to change the type of the element itself in the stream or only want the internal state of the element; and map Is used to change the type of the element itself in the stream, that is, the operation of deriving another type from the element. This is the biggest difference between them.
So what scenarios do we actually use peek for? example, for Stream<T> of T Used when batch processing certain attributes of peek Operation is more appropriate. If we're going to start Stream<T> obtained T Use when a collection of a certain attribute of map That would be the best.

4. summary

We understand today Stream the peek Operation, and also reviewed Stream life cycle. Also incidentally, Consumer<T> Function is explained. and with map We compared each other and explained their respective usage scenarios. I believe you will have a deeper understanding of them after reading this article.

read more
Resource download
PriceFree
The use is limited to testing, experiments, and research purposes. It is prohibited for all commercial operations. This team is not responsible for any illegal behavior of users during use. Please self-test all source codes! There is no guarantee of the integrity and validity of your source code. All source code is collected from the entire network
Original link:https://bcbccb.cn/en/4447.html, please indicate the source for reprinting. Disclaimer: This resource has not been authorized by the original rights holder and is not commercially available. It can only be used to learn and analyze the underlying code, CSS, etc., and is prohibited for commercial purposes. Any relevant disputes and legal liabilities arising from unauthorized commercial use shall be fully borne by the user. Everyone is responsible to support genuine copies. Please delete them within 24 hours after downloading. Thank you for your support!
1

Comments0

【最新更新】ZN7号_微盘wp二开版带余额宝功能时间盘黄金期货数字火币交易+完整数据+k线正常
[Latest update] ZN No. 7_microdisk wp second edition with balance treasure function Time disk gold futures digital hot coin trading + complete data +k line normal
Someone bought it 8 minutes ago Go and have a look

Site Announcements

The source code (theme/plug-in/application source code) and other resources provided by this site are only for learning and exchange

Commercial use is prohibited, otherwise all consequences will be borne by the downloading user!

Some resources are collected or copied online. If they infringe on your legitimate rights and interests, please write to us.

Currently, members have a big reward, and the current price for a lifetime member is 299 gold coins.Recent price adjustments

Join quickly, opportunities wait for no one! immediately participated in

Captcha

Fast login to social accounts

en_USEnglish