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

share...Share on LinkedIn4Share on Google+0Share on Facebook0
The following two tabs change content below.
Arulkumaran Kumaraswamipillai
Mechanical Engineer to freelance Java developer within 3 years. Freelancing since 2003 for the major banks, telecoms, retail & government organizations. Attended 150+ Java job interviews, and most often got 3-6 job offers to choose from. 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 Engineer to freelance Java developer within 3 years. Freelancing since 2003 for the major banks, telecoms, retail & government organizations. Attended 150+ Java job interviews, and most often got 3-6 job offers to choose from. 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+ Java Interview Q&As – ♥ Free | ♦ FAQs

open all | close all

Pressed for time? 200+ Quick Prep

open all | close all

16 Java Key Areas to be a top-notch

open all | close all

100+ 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