User Tools

Site Tools


java_api_8

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
java_api_8 [2016/11/02 14:12]
178.237.8.52 [Terminal Operation / Collection]
java_api_8 [2016/11/02 14:24] (current)
178.237.8.52 [Stream API]
Line 1: Line 1:
 ====== Stream API ====== ====== Stream API ======
  
-The ''​stream'' ​API is a step in the field of functional programming,​ that is a different programming style that is more declarative. It is actually much more similar to SQL than to OOP. At any rate, Java introduced the ''​Stream API''​ and the ''​lambda''​ to go in this direction.+The [[https://​docs.oracle.com/​javase/​8/​docs/​api/​java/​util/​stream/​package-summary.html#​package.description | stream API]] is a step in the field of functional programming,​ that is a different programming style that is more declarative. It is actually much more similar to SQL than to OOP. At any rate, Java introduced the ''​Stream API''​ and the ''​lambda''​ to go in this direction.
  
 ===== The pipeline ===== ===== The pipeline =====
Line 152: Line 152:
      ​return result;      ​return result;
 </​code>​ </​code>​
 +
 +So with the ''​supplier''​ you create an object where to store the result (e.g. an ArrayList), the accumulator calls the functional interface that is a ''​BiConsumer''​ and gets 2 elements and combines them (e.g. ''​.add()''​ in an ArrayList). Lastly, if the operation is performed in parallel the combiner combines the result together in another type ''​R''​ container by using its ''​accept''​ method.
 +
 +For example, the following will accumulate strings into an ArrayList:
 +<code java>
 +
 +List<​String>​ asList = stringStream.collect(ArrayList::​new, ​
 +                                           ​ArrayList::​add,​
 +                                           ​ArrayList::​addAll);​
 +</​code>​
 +
 +The following will take a stream of strings and concatenates them into a single string:
 +<code java>
 +
 +String concat = stringStream.collect(StringBuilder::​new, ​
 +                                     ​StringBuilder::​append,​
 +                                     ​StringBuilder::​append)
 +                            .toString();​
 +</​code>​
 +
 ===== Example ===== ===== Example =====
  
java_api_8.1478095938.txt.gz ยท Last modified: 2016/11/02 14:12 by 178.237.8.52