User Tools

Site Tools


java_api_8

This is an old revision of the document!


A PCRE internal error occured. This might be caused by a faulty plugin

====== 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 pipeline ===== A ''stream'' is a pipeline to elaborate data. It provides the normal control-flow mechanism in a different way. A ''stream'' is characterized by 3 elements: * a start (where we supply data), * a middle (elaboration), * an end (where we collect the data). ==== Begin ===== The beginning of the pipeline must provide the data. There are a few ways to provide data: from data or by generating it. <code java> String[] stringArr = {"a", "b", "c", "d"}; Stream<String> stream = Arrays.stream(stringArr); // from arrays Collection<String> list = new Arrays.asList("one" , "two" , "three"); Stream<String> s1 = list.stream(); // from collections Stream<String> s2 = Stream.generate(()->"generate"); // a continuos stream generated by a Supplier // functional interface with get abstract method Stream<String> s3 = Stream.iterate("0" , i -> ++(char)i); Stream<Integer> s4 = Stream.iterate(0, i-> ++i); // generates or better iterates from natural numbers. // It Autoboxes so it does not perform well. // Iterating on numbers it's better // done with appropriate primitive streams. IntStream is5 = IntStream.iterate(0, i -> ++i); // notice that the lambda has a pre-increment otherwise an // infinite stream of 0-s is generated IntStream s6 = IntStream.iterate('0', x -> ++x); s6.limit(25).mapToObj(x->((char)x)).forEach(x->System.out.print(x + " ")); </code> ==== Middle (Elaboration) ===== ==== Terminal Operation / Collection ==== A stream is lazily created and executed. So it won't work unless you terminate it. Most common terminations are: * ''collect()'', it collects the result of the stream into a mutable objects as Collection * ''reduce()'', reduce the stream to a single object based on some rules defined with functional interfaces. * find matches: they use a ''Predicate<? super T>'' to determine the match. * ''allMatch()'', returns whether **all** elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. * ''anyMatch()'', returns whether **any** elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then false is returned and the predicate is not evaluated. * ''noneMatch()'', returns whether **no** elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. * ''findAny()'', returns an ''Optional'' describing some element of the stream, or an empty ''Optional'' if the stream is empty. * ''findFirst()'', returns an ''Optional'' describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned. * ''forEach()'', iterates on the elements of the stream allowing some operation to be done, but does not return. **Hangs on infinite streams**. * ''min()'' ''max()'', determine the min and the max value in the stream according to an optional comparator. Return an Optional. **Hangs on infinite streams**. * ''count()'', determines the number of elements in the stream. **Hangs for infinite streams**. === ''reduce()'' === The signature is <code java> Optional<T> reduce(BinaryOperator<T> accumulator) T reduce(T identity, BinaryOperator<T> accumulator) <U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner) </code> ===== Example ===== <code java StreamExercise.java> import java.util.*; import java.util.stream.*; public class StreamExercise { public static void main(String[] args) { // calculate the sum of an array List<Integer> list = Arrays.asList(0,1,2,3); int thesum = list.stream() //create the stream .reduce(0,(a,x)->a+x); // elaborate and return System.out.println(thesum); // 6 // data from a Supplier Stream<Integer> s = Stream.iterate(0, n -> n+1); Integer i = s.limit(4) .reduce(0, (a,x) -> a + x ); System.out.println(i); // 6 } } </code>

java_api_8.1478084285.txt.gz · Last modified: 2016/11/02 10:58 by 178.237.8.52