06: Java 8 way of File reading and functionally processing the data

Output:


#1 double colon notation ::

The new double colon (::) operator that Java 8 has to convert a normal method into lambda expression. So,

Instead of:

You can do:


#2 Why is stream::iterator used?

lines::iterator” where iterator() is an instance method on “BaseStream<T,Stream<T>>” from which java.util.Stream<T> extends. The “iterator()” returns an “Iterator<T>”. The for each loop works on Iterable<T>.

So, given a Stream s, the following results in an Iterable:

If you want to use this directly in an enhanced-for loop, you have to apply a cast in order to establish a target type for the method reference.


#3 Iterator Vs Iterable difference?

An Iterable<T> is a simple representation of a series of elements that can be iterated over, and it does not have any iteration state such as a “current element”. Instead, it has a “iterator()” method that produces an Iterator. Implementing this interface allows an object to be the target of the “for-each loop” statement.

An Iterator<T> is the object with iteration state to let you check if it has more elements using hasNext() and move to the next() element.

Read from the classpath

Output:

Filter the line that has “fox”

Output:

Note: filter() is an intermediate operation, returning a Stream, and findFirst() is a terminal operation.

Count lines

Output:

Note: count() is a terminal operation as it does not return a stream.

Can you workout the output of the following code?

Output:

An array of size two containing …..

(Visited 7 times, 1 visits today)

800+ Java Interview Q&As

Java & Big Data Tutorials

Top