Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly find the stream characteristics in Java-8?

While doing stream operations, during the intermediate/pipeline operations the streams would be created with different characteristics(e.g: SORTED/SIZED/DISTINCT/ORDERED) - Mastering Lambdas(Ch 6)

Stream.of(8,3,5,6,7,4) // ORDERED, SIZED
.filter(i->i%2==0) // ORDERED
.sorted() // ORDERED, SORTED
.distinct() // DISTINCT, ORDERED, SORTED
.map(i->i+1) // ORDERED
.unordered(); // none

How do we find out the different characteristics of the stream as mentioned in the above snippet?

like image 629
Chota Bheem Avatar asked Jun 11 '17 16:06

Chota Bheem


People also ask

What would be a good way of describing streams in Java 8?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.

How many types of streams does Java 8 have?

Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.

How do I read a Java stream?

Java Streams are basically a pipeline of aggregate operations that can be applied to process a sequence of elements. An aggregate operation is a higher-order function that receives a behaviour in a form of a function or lambda, and that behaviour is what gets applied to our sequence.

How do I get unique values from a stream?

distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable.


1 Answers

At each stage you can call:

int c = stream.spliterator().characteristics();

And then test the result against the constants defined in the Spliterator class. For example to see if the stream is ordered:

boolean isOrdered = (c & Spliterator.ORDERED) == Spliterator.ORDERED;

Alternatively you can use:

boolean isOrdered = stream.spliterator().hasCharacteristics(Spliterator.ORDERED);
like image 138
assylias Avatar answered Oct 19 '22 02:10

assylias