Java 8 API


Introduction to Java 8 API

The following article provides an outline for Java 8 API. Java 8 is an extensive release of the world’s best enterprise programming language. It incorporates a tremendous move up to the Java programming model and planned development of the Java Virtual Machine (JVM), Java language, and libraries. Java 8 incorporates highlights for efficiency, convenience, worked on multilingual programming, security, and further developed execution. The option of the Stream, Lambda Expression, and file I/O was one of the significant highlights added to Java 8.

Key Takeaways

  • Functional programming and lambda expression
  • Java optional
  • Default methods in interfaces
  • Java file I/O
  • Date and time API
  • Java concurrency and parallelism
  • Improvements in collection API

What is Java 8 API?

Java 8 introduced another Programming interface (called Streams) that upholds many equal tasks to deal with information and looks like the manner in which you could think in data set question dialects — you express what you need in a more elevated level way, and the execution picks the best low-level execution system. Which results in avoiding writing code that uses synchronization. Synchronization is not only highly error-prone but also expensive on multicore CPUs.

Be that as it may, considering passing code to strategies a simple outcome of Streams makes light of its scope of purposes inside Java 8. It gives you another brief idea about using methods as parameters. Assume one needs to compose two techniques that vary in a couple of lines of code; they can now pass the code of the parts that contrast as an argument.

The Java 8 component of passing code to strategies likewise gives admittance to an entire scope of extra methods that are generally alluded to as Functional Programming. Basically, such codes are called functions that can be passed around and joined in a manner to create strong programming expressions.

What is Java 8 API Stream?

Stream is basically a sequence of data flowing from a source to a sink, and they can be manipulated via operations like map, reduce, aggregate, etc, via Java 8 APIs. It is functional in nature. Tasks performed on a stream don’t change their source. For instance, separating a Stream got from an assortment creates another Stream without the sifted components, as opposed to eliminating components from the source assortment. Stream evaluates the code only when it is required.

There are various operations on Stream. Some of the major operations are:

1. Map

The map operation is utilized to return a stream comprising of the consequences of applying the given function to the components of this stream.

Code:

List<int> numList = Arrays.asList(2,3,4,5);
List square = numList.stream().map(x->x*x)
.collect(Collectors.toList());

2. Filter

The filter operation is utilized to choose components and eliminate them according to the criteria.

Code:

List<String> nameList = Arrays.asList("Reflection","Collection","Stream");
List result = nameList.stream().filter(s->s.startsWith("S"))
.collect(Collectors.toList());

3. Sorted

The sorted operation is used to sort the stream.

Code:

List<String> nameList = Arrays.asList("Reflection","Collection","Stream");
List result = nameList.stream().sorted()
.collect(Collectors.toList());

4. Reduce

The Reduce operation is utilized to diminish the components of a stream to a solitary value. It takes a binary operator as the input parameter.

Code:

List<int> numberList = Arrays.asList(2,3,4,5);
int even = numberList.stream().filter(x->x%2==0)
.reduce(0,(ans,i)-> ans+i);

A simple code to demonstrate stream operation in Java 8.

Code:

import java.util.*;
import java.util.stream.*;
class DemoApp

public static void main(String args[])

// create a list of integers
List<Integer> numberList = Arrays.asList(2,3,4,5);
// demonstration of map method to find a square
List<Integer> squareList = numberList.stream().map(x -> x*x).
collect(Collectors.toList());
System.out.println(squareList);
// create a list of String
List<String> nameList =
Arrays.asList("Reflection","Collection","Stream");
// demonstration of filter method to filter Strings starting with “S”
List<String> result = nameList.stream().filter(s->s.startsWith("S")).
collect(Collectors.toList());
System.out.println(result);
// demonstration of sorted method
List<String> sortedList =
nameList.stream().sorted().collect(Collectors.toList());
System.out.println(sortedList);
// create a list of integers
List<Integer> numbers = Arrays.asList(2,3,4,5,2);
// collect method returns a set
Set<Integer> squareSet =
numbers.stream().map(x->x*x).collect(Collectors.toSet());
System.out.println(squareSet);
// demonstration of forEach method
numberList.stream().map(x->x*x).forEach(y->System.out.println(y));
// demonstration of reduce method
int even =
numberList.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);
System.out.println(even);

Output:

Java 8 API - Stream Operation

What are Arrays in Java 8?

Java array is an object which contains elements of a similar data type. Additionally, the elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array. Java 8 has added a stream class for arrays that work on coherence as well as productivity. Changing arrays over stream additionally expands the general presentation of the program.

Likewise, you can likewise utilize the different Stream Programming interface strategies that can improve planning and separating activities on clusters.

Let’s understand this with the help of a simple program.

Code:

import java.util.Arrays;
class GFG_Demo_1 
public static void main(String[] args)

int intArr[] =  1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ;
// Let's try the imperative style first(which we
// are familiar with)
int sum = 0;
for (int i = 0; i < intArr.length; i++)
sum += intArr [i];
System.out.println("Average using iteration :" +
(sum / intArr.length));
// Let's try the declarative style now
sum = Arrays.stream(intArr) // Step 1
.sum(); // Step 2
System.out.println("Average using streams : " +
(sum / intArr.length));
// forEach()
// It iterates through the entire streams
System.out.println("Printing array elements : ");
Arrays.stream(intArr)
.forEach(e->System.out.print(e + " "));

Output:

Java 8 API Clusters

Understanding String and File

The String class represents character strings. All string literals in Java programs, such as “abc”, are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable, they can be shared. There are new features where they started using streams for file management.

Code:

System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);

Files

The utility class Files was first introduced in Java 7 as part of Java NIO. The JDK 8 API adds a couple of additional methods which enable us to use functional streams with files.

1. Listing Files

The method Files.list streams all paths for a given directory, so we can use stream operations like filter and sorted upon the contents of the file system.

Code:

try (Stream<Path> fileStream = Files.list(Paths.get(""))) 
String joined = fileStream
.map(String::valueOf)
.filter(path -> !path.startsWith("."))
.sorted()
.collect(Collectors.joining("; "));
System.out.println("List: " + joined);

2. Finding Files

The next example demonstrates how to find files in a directory, or it’s sub-directories.

Path start = Paths.get("");
int maxDepth = 5;
try (Stream<Path> fileStream =
Files.find(start, maxDepth, (path, attr) ->
String.valueOf(path).endsWith(".js"))) 
String joined = fileStream
.sorted()
.map(String::valueOf)
.collect(Collectors.joining("; "));
System.out.println("Found: " + joined);

3. Reading and Writing Files

Reading text files into memory and writing strings into a text file in Java 8 is finally a simple task. No messing around with readers and writers. The method Files.readAllLines reads all lines of a given file into a list of strings. You can simply modify this list and write the lines into another file via Files.write:

Code:

List<String> lines = Files.readAllLines(Paths.get("res/nashorn1.js"));
lines.add("print('foobar');");
Files.write(Paths.get("res/nashorn1-modified.js"), lines);

Methods and Parameters

Given below shows the methods and parameters:

1. Functional Programming

It is a revelatory way of programming as opposed to basic. The essential target of this way of writing computer programs is to make code briefer, less mind-boggling, and simpler to test, contrasted with the heritage way of coding. Functional programming manages specific key ideas, for example, unadulterated capability, unchanging state, task-less programming, and so on.

Implementing a functional program on Java.

Code:

import java.util.Arrays;
import java.util.List;
public class TestClass 
public static void main(String[] args)

// Defining an anonymous method
Runnable r = new Runnable() 
public void run()

System.out.println(
"Running in Runnable thread");

;
r.run();
System.out.println(
"Running in main thread");

Output:

Functional Programming

2. Lambda Expressions

Lambda expressions fundamentally express examples of functional programming. Lambda expressions carry out the main conceptual capability and hence execute useful connection points.

Lambda expressions in Java 8 give the following functionalities:

  • Treat functionality as a method argument, code, or data set.
  • No class is required to create a function.
  • If an object is executed on demand, then the Lambda expression can be passed.

A simple program on how to use Lambda Expression.

Code:

interface TestFuncInterface

// An abstract function
void abstractFun(int x);
// A non-abstract (or default) function
default void normalFun()

System.out.println("Hello");

Who are the Clients for Java 8 API?

HTTP Client gives coordinated and offbeat solicitation components. The Programming interface comprises three center classes:

  • HTTP Request addresses the solicitation to be sent by means of the HTTP Client.
  • HTTP Client acts as a holder for setup data normal to various solicitations.
  • HTTP Response addresses the consequence of an HTTP Request call.

Conclusion

In Java 8, the main thing i.e. the big boiler code. It increases the speed of the code as compared to the previous versions. The main enhancements were the lambda expressions, API streams, and new methods on existing classes.

Recommended Articles

This is a guide to Java 8 API. Here we discuss the introduction, what is java 8 API stream, string, and file, methods, and parameters. You may also have a look at the following articles to learn more –

  1. Text File in Java
  2. Java 8 forEach
  3. Java for Automation Testing
  4. Java SFTP

The post Java 8 API appeared first on EDUCBA.



Source link

Leave a Reply

Your email address will not be published.