본문 바로가기
Programming/Java

Stream

by peter paak 2019. 3. 9.
728x90

Stream

java.tuil.stream
Stream<T>


Stream Creation

Stream can be created with the help of stream() and of() method


Array

Stream<String> stream = Arrays.stream(array);

stream = Stream.of("a","b","c")

Collection

Stream<String> stream = list.stream();


Multi-threading with Streams

parallelStream() method

list.parallelstream().forEach(element -> doWork(element));


Stream Operations

Iterating

Substitute for, forEach, while loops. It allows concentrating on operation’s logic.

boolean isExist = list.stream().anyMatch(element -> element.contains("a"));


Filtering

filter() method allows us to pick stream of elements which satisfy a predicate

  • Finds all elements of this stream which contain char “d”
  • creates a new stream containing only the filtered elements
Stream<String> stream = list.stream().filter(element -> element.contains("d"));


Mapping

To validate elements of a sequence according to some predicate

  • anyMatch()
  • allMatch()
  • noneMatch()
boolean isValid = list.stream().anyMatch(element -> elemnt.contains("1"));
boolean isValidOne = list.stream().allMatch(element -> elemnt.contains("1"));
boolean isValidnone = list.stream().noneMatch(element -> elemnt.contains("1"));


Reduction

Reduce a sequence of elements to some value according to a specified function with the help of the reduce()method of the type Stream

Integer reduced = integers.stream().reduce(23, (a, b) -> a + b);


Collecting

Reduction can also be provided by the collect() method of type Stream
It could be very handy in case of converting a stream to Collection or a Map

Collectors provide a solution for almost all typical collecting operation



Methods

sum()

Return sum of element in the stream
This is special case of Reduction


mapToInt

Return a int stream consisting of the results of applying the given function to the elements of this stream.

param : function to apply to each element
Return : new stream


Double colon (::) operator in Java - GeeksforGeeks


728x90