简体   繁体   中英

How terminal operation in java 8 Stream API called intermediate operation

In java 8, Intermediate Operation add the listener like they are mean for lazy processing and whenever any terminal operation is called then that terminal operation will call each of these listener one by one sequentially and finally terminal operation will prepare the result depending upon type of operations and close the stream. So I want to understand that how these listener is added and how terminal operation internally called these intermediate operations listener.

Example:-

List<String> countries= Arrays.asList("India","Austriala","America","Japan","England","Germany");

countries.stream().map(s -> s.length()).max(Integer :: compare).get();

Map<Integer,Set<String>> map = countries.stream().collect(Collectors.groupingBy(String::length, Collectors.toSet()));
map.entrySet().forEach(System.out :: println);

Here we are using one intermediate operation map and max is the terminal operation.

Simple enough: countries is a stream. countries.map(s -> s.length()) creates a new object. This object contains 2 things:

  • That stream
  • The code s -> s.length() as a function.

That's all. It doesn't process the stream. It is, itself, a stream. If you ask this stream to provide data, it will start reading its inner stream, and tossing the objects that fall out of that inner stream at the function it has, then, it provides those.

Only the terminal op starts asking the stream you invoked the terminal on (the X in X.max ) for data, which then 'sets the train in motion'. That X will start producing data, and in order to do so, assuming X is an intermediate, it will ask the Y that you called it on (The Y in Y.map(s -> s.length()) , and so on.

Java's core libraries are all open source.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM