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 …..

Print Friendly
The following two tabs change content below.
Arulkumaran Kumaraswamipillai
Mechanical Engineering to Java freelancer since 2003. Published Java/JEE books via Amazon.com in 2005, and sold 35K+ copies. Books are outdated and replaced with this online Java training. join my LinkedIn group.
Arulkumaran Kumaraswamipillai

Mechanical Engineering to Java freelancer since 2003. Published Java/JEE books via Amazon.com in 2005, and sold 35K+ copies. Books are outdated and replaced with this online Java training. join my LinkedIn group.

Posted in IO, Java 8
Tags:

800+ Interview Q&As with lots of diagrams & code ♥Free | ♦FAQs | Hover/Slide for full text

open all | close all

200+ Java Interview FAQs – Quick Prep

open all | close all

16 Java Key Areas to be a top-notch

open all | close all

80+ Java Tutorials – Step by step

open all | close all

100+ Java Coding Exercises

open all | close all

How good are your

open all | close all