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

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. 1,350+ paid memberships.
Tags:

By topics – 800+ Q&As ♥ Free ♦ FAQ

open all | close all

Java 200+ FAQs – Quick Brushup

open all | close all

100+ Java Tutorials step by step

open all | close all

13+ Tech Key Areas to standout

open all | close all

Java coding exercises

open all | close all
Top