How to run JavaScript embedded in java program using Nashorn JavaScript Engine??

 Nashorn JavaScript Engine

              It is a JavaScript engine introduced in java8. It was developed by oracle. Now, it is under the OpenJDK community.

Purpose:

This is used to run the JavaScript code in JVM (Java Virtual Machine).

Why Nashorn?

It is efficient in execution compared to previous one (Rhino Engine).

It easily integrates java and JavaScript. The user can simply use the command line.

How to run JavaScript embedded in java program using Nashorn JavaScript Engine??

              Here, java Script is a single line which displays a greetings “Happy Programming”.

Steps:

  • Import three built in packages from javax.script(.ScriptEngine,.ScriptEngineManager,.ScriptException)
  • Create a public class NashornEg and save the file as “NashornEg.java”
  • Inside the main() function,create an object for ScriptEngineManager as mgr.
  • Get the Nashorn script Engine.
  • Write a java script code.
  • Eval the script by Object result1 = engine1.eval(script);
  • Print the result.

import javax.script.ScriptEngine;

import javax.script.ScriptEngineManager;

import javax.script.ScriptException;

public class NashornEg {

    public static void main(String[] args) {

        // Create an object for ScriptEngineManager

        ScriptEngineManager mgr = new ScriptEngineManager();

       // find the Nashorn script engine

        ScriptEngine engine1 = mgr.getEngineByName("nashorn");

      // JavaScript code

        String script = "var greetings = 'Happy Programming!';";

        try {

            // create an object and call the function

            Object result1 = engine1.eval(script);

           // Print the output

            System.out.println(result1);

        } catch (ScriptException e) {

            e.printStackTrace();

        }

    }

}

  • Compile the program.
  • If the compilation is successful, run the program.

C:\raji\blog>javac NashornEg.java

C:\raji\blog>java NashornEg

Happy Programming!

Let us try some more scripting….

Java Script to display “Happy Birthday. Stay Blessed Always!!!!”.

Same program is used with java script code alone changed.

        String script = "var bMsg = 'Happy Birthday. Stay Blessed Always!!!!';";

Change the code. Execute the same program as below.

C:\raji\blog>javac NashornEg.java

C:\raji\blog>java NashornEg

Happy Birthday. Stay Blessed Always!!!!

That’s all. The java program to use JavaScript within the code is developed successfully.

Note: This JavaScript engine is used as standalone project on GitHub because it was deprecated in java11.

How to implement Static methods in interface concept in java8???

  The word “Static” is applicable for the interface. It does not be an instance of the class which implements the interface.

Why static method???

  • ·       Scope of the static methods is visible within interface.
  • ·       It belongs to interface only. So, utility methods are declared as static methods.

Simple program to implement static methods in interface:

              This program creates an interface with a static method “staticMd()” to print the static method message. Even though, a class is declared to implement the interface, the method belongs to the interface only.

//Java Program to implement static methods in interface

interface MyInter {

    static void staticMd() {

        System.out.println("This is a static method in an interface MyInter");

    }

}

public class MyCls implements MyInter {

    public static void main(String[] args) {

        MyInter.staticMd(); // Function call

    }

}

Save this file as “MyCls.java”.

Compile the program in command prompt.

C:\raji\blog>javac MyCls.java

Execute the program as follows. You will get this output.

C:\raji\blog>java MyCls

This is a static method in an interface MyInter.

 Next, a program for odd or even number checking is given below.

Java Program to implement Odd/Even number checking using static methods in interface:

              This java program has following steps to implement the concept.

  • Create an interface “MyInter1”.
  • Inside the interface, implement the static method as “static void staticOddEven(int a)”.

         Where,

        static – keyword.

        void – return type.(It doesn’t return anything)

        staticOddEven – this is the static function name.

        int a – input of a function as integer.

  • This function checks the given number is odd or even and print it.
  • Create a class “MyCls1” to implement the interface “MyInter1”.
  • Inside it,create a main function.
  • Call the static function “MyInter1.staticOddEven(6)”.

// Java Program to implement Odd/Even number checking using static methods in interface

interface MyInter1 {

    static void staticOddEven(int a) {

      if(a%2==0)

        System.out.println("The number is a even number");

      else

       System.out.println("The number is a even number");

          }

}

public class MyCls1 implements MyInter1 {

    public static void main(String[] args) {

        MyInter1.staticOddEven(6); // static method call

    }

}

Compile and run the program to get the output.

C:\raji\blog>javac MyCls1.java

C:\raji\blog>java MyCls1

The number is a even number

These are the ways to implement the static methods in interface concept in java8. Keep Coding!!!!

How to display a vehicleList using forEach in java8 programming?

              Java8 offers variety of concepts like lambda expressions, functional interfaces, streams, default methods, collectors and so on…

“Foreach” is an added feature for looping to iterate the elements. It uses lambda expression or looping.

Java Program to display the vehicle list using ForEach method using Lambda expressions:

Steps to follow:

  • ·       This program creates a vehicleList as string.
  • ·       Add the list of vehicles to vehicleList.
  • ·       Using lambda expression, ForEach method dispalys the vehicleList.

//Java Program to display the vehicle list using ForEach method using Lambda expressions:

import java.util.ArrayList; 

import java.util.List; 

public class ForEachEg { 

  public static void main(String[] args) { 

                      List<String> vehicleList = new ArrayList<String>(); 

                      vehicleList.add("Car"); 

                      vehicleList.add("Bike"); 

                      vehicleList.add("Truck"); 

                      vehicleList.add("Bus"); 

                             vehicleList.add("Auto");

                      System.out.println("------------Example of passing lambda expression--------------"); 

                      vehicleList.forEach(vehicle -> System.out.println(vehicle)); 

                  } 

              }

Compile and run the program to get the output as shown below. 

C:\raji\blog>javac ForEachEg.java

C:\raji\blog>java ForEachEg

------------Example of passing lambda expression--------------

Car

Bike

Truck

Bus

Auto

Next program is using foreach as looping.

Java Program to display the vehicle list using ForEach method using Looping:

              This program uses the looping to iterate the elements. It has steps to follow to create this program.

Steps:

  • ·       Import the built in packages java.util.ArrayList and java.util.List
  • ·       Create a public class ForEachEg1 and save the program as “ForEachEg1.java”.
  • ·       Inside the main function, create list as “vehicleList”.
  • ·       Add the vehicles to vehicleList.
  • ·       Print the list using forEach() method.

// Java Program to display the vehicle list using ForEach method using Looping

import java.util.ArrayList; 

import java.util.List; 

public class ForEachEg1 { 

    public static void main(String[] args) { 

        List<String> vehicleList = new ArrayList<String>(); 

              vehicleList.add("Car"); 

              vehicleList.add("Bike"); 

              vehicleList.add("Truck"); 

              vehicleList.add("Bus"); 

              vehicleList.add("Auto");

        System.out.println("------------Iterating by passing method reference---------------"); 

        vehicleList.forEach(System.out::println); 

    } 

} 

  • Open the command prompt. Set the path for java.
  • Compile the program .

C:\raji\blog>javac ForEachEg1.java

  • Run the program to display the output.

C:\raji\blog>java ForEachEg1

------------Iterating by passing method reference---------------

Car

Bike

Truck

Bus

Auto

These are the ways to implement ForEach method to iterate elements.

How to use Collectors in java8?

    When a java8 program runs in the stream, the ending process is with collectors. It shows the way to collect the data from stream and put it into a structure which stores the data. The structure is a list, a set or a map.

It collects the data, organize it and arrange the data according to the criteria given by the user.

Here, the list of collectors is given below.

  • 1.       List
  • 2.       Set
  • 3.       Map

Next, the java programs to implement these collectors are coded with simple examples.

1.Java Program to display a stream of data using List:

              This program creates a stream of data as a string. Create a list and store the data from the stream.

Print the list.

// Java Program to display a stream of data using List

import java.util.stream.Collectors;

import java.util.List;

import java.util.stream.Stream;

public class CollectorsEg {

public static void main(String[] args) {

Stream<String> stringSt = Stream.of("HTML", "JavaScript", "Web Server", "JScript");

List<String> sList = stringSt.collect(Collectors.toList());

System.out.println(sList);

}

}

When you execute this program, you will get the below output.

C:\raji\blog>javac CollectorsEg.java

C:\raji\blog>java CollectorsEg

[HTML, JavaScript, Web Server, JScript]

2.Java Program to display a stream of data using Set:

              A stream of data is collected as a set. print the set.

 // Java Program to display a stream of data using set

import java.util.stream.Collectors;

import java.util.Set;

import java.util.stream.Stream;

public class CollectorsEg1 {

public static void main(String[] args) {

Stream<String> stringSt = Stream.of("HTML", "JavaScript", "Web Server", "JScript");

Set<String> set = stringSt.collect(Collectors.toSet());

System.out.println(set);

}

}

The output is given below.

C:\raji\blog>javac CollectorsEg1.java

C:\raji\blog>java CollectorsEg1

[JScript, JavaScript, Web Server, HTML]

3.Java Program to display a stream of data using Map:

              This program collects the data as map. Here, creates a string with expansions. Next, convert it into map by using  toMap() function. Print the data.

// Java Program to display a stream of data using Map

import java.util.stream.Collectors;

import java.util.stream.Stream;

import java.util.*;

public class CollectorsEg2{

    public static void main(String[] args)

    {

      Stream<String[]>

            str1 = Stream

                      .of(new String[][] { { "HTML", "HyperText Markup Language" },

                                           { "CSS", "Cascading Stylesheets" },

                                           { "WWW", "World Wide Web" } });

          Map<String, String>

            map1 = str1.collect(Collectors.toMap(p -> p[0], p -> p[1]));

                 System.out.println("Map:" + map1);

    }

}

Compile and execute the program to get the output.

C:\raji\blog>javac CollectorsEg2.java

C:\raji\blog>java CollectorsEg2

Map:{CSS=Cascading Stylesheets, WWW=World Wide Web, HTML=HyperText Markup Language}

These are the ways to implement collectors in java8. Happy Coding!!!!

How to write a java8 program to implement Date and Time API?

     Each and every nanosecond is important in computer operations. So Date and Time calculation plays a vital role in computer programming. Java8 offers a new Date and Time API for the enhancement of built in packages java.util.Date and java.util.Calendar.

 What are the new features added in these API???

  • ·       Concise methods: It consists of simple and concise methods.
  • ·       Wide range of classes:  This API has variety of classes for different date and time zones.
  • ·       Thread safe API :If the instance is created, it is not changeable.

List of important classes:

              API includes wide range of built in classes. Here, the important classes are listed down.

Built in Class

Purpose

Format

Eg

LocalTime

It provides a time without date.

Hours:Minutes:Seconds

21:32:14

LocalDate

It gives a date without time

Year – Month - Day

2024-09-11

LocalDateTime

It shows Date and Time without any time zone

Year- Month- Day

THours:Minutes:Seconds

2024-09-11

21:32:14T

ZonedDateTime

It displays Date and Time with time zone

Year- Month- Day

THours:Minutes:Seconds +05:30[ Asia/Kolkata]

2024-09-11

21:32:14

+05:30[ Asia/Kolkata]

 

How to write a java8 program to implement Date and Time API?

Date and time API implementation can be done by two ways.

  1.    Displaying Date and Time

  2.       Implementing ZoneddateTime

Each implementation is given below.

 1.    Displaying Date and Time:

This java8 Program displays Date and Time. It includes the following steps.

·       Include the built in packages java.time.LocalDate,java.time.LocalTime, java.time.LocalDateTime.

·       Create a public class “DateTimeEg” and save this file as “DateTimeEg.java”.

·       Inside the main function, create three objects for LocalDate,LocalTime, LocalDateTime as date1,time1,dateTime1.

·       Using the objects,call the now function for each objects by as follows.

·       date1.now(),time1.now(), dateTime.now().

·       Print the date,time and  datetime.

Here, is the program.

Java8 program to display date,time,datetime :

import java.time.LocalDate;

import java.time.LocalTime;

import java.time.LocalDateTime;

public class DateTimeEg {

    public static void main(String[] args) {

        LocalDate date1 = LocalDate.now();

        LocalTime time1 = LocalTime.now();

        LocalDateTime dateTime1 = LocalDateTime.now();

        System.out.println("Today's Date is: " + date1);

        System.out.println("The Current Time is: " + time1);

        System.out.println("The date and time is: " + dateTime1);

    }

}

Open the command prompt. Set the path. Compile and Execute the program as follows.

C:\raji\blog>javac DateTimeEg.java

C:\raji\blog>java DateTimeEg

Today's Date is: 2024-09-11

The Current Time is: 09:41:16.593843

The date and time is: 2024-09-11T09:41:16.593843

2.Implementing ZoneddateTime

              This java8 program deals with ZoneDateand time. To implement zonedDateTime,follow the steps.

  • Import the built in packages “java.time.ZonedDateTime, java.time.ZoneId”.
  • Create a class “ZonedDateTimeEg” and save this file as “ZonedDateTimeEg.java”.
  • Inside the main function, create object for ZonedDateTime and call the now function.
  • Display the current zone time with print statement.

#Java Program to implement ZoneddateTime

import java.time.ZonedDateTime;

import java.time.ZoneId;

public class ZonedDateTimeEg {

    public static void main(String[] args) {

        ZonedDateTime zDateTime1 = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));

        System.out.println("The Current Date and Time in Asia/Kolkata zone is: " + zDateTime1);

    }

}

Follow the steps to get the output.

C:\raji\blog>javac ZonedDateTimeEg.java

C:\raji\blog>java ZonedDateTimeEg

The Current Date and Time in Asia/Kolkata zone is: 2024-09-11T10:23:18.010432100+05:30[Asia/Kolkata]

These are all the ways to implement date and time API in java.

How to create Optional Class in java 8?

              If you want to create a code that helps in excessive null checks and Null pointer Exception. Java8 offers this feature as “Optional Class”.

Built in package used to implement optional class is “java.util”.

How to create Optional class in java?

  • First, a java program is created to show the NullPointerException.
  • This program includes a class “OptionalCls”. Inside the main function, a string variable “str” is created with 10 spaces.
  • Another string “sample” is assigned with a string “str”.Third element is converted into Uppercase and stored in sample.
  • Finally, print the sample value.

Here, is the program.

public class OptionalCls {

    public static void main(String[] args)

    {

        String[] str = new String[10];

        String sample = str[3].toUpperCase();

        System.out.print(sample);

    }

}

After the completion of this program, Open command Prompt.

Set the path.

Compile the program as follows.

C:\raji\blog>javac OptionalCls.java

Next, Run the program.

C:\raji\blog>java OptionalCls

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "<local1>[3]" is null

        at OptionalCls.main(OptionalCls.java:5)

There is no data in str. So, it shows NullPointerException.

To avoid this null exception, let us include the optional class.

The next program shows to include Optional Class.

  • ·       This program creates a String variable “checkNull” with the value “Optional.ofNullable”.
  • ·       If “checkNull.isPresent” is true, it executes the loop.
  • ·       Otherwise, it prints “The word is null”.

Program to implement Optional Class:

import java.util.Optional;

public class OptionalCls1 {    

    public static void main(String[] args)

    {

        String[] str = new String[10];

        Optional<String> checkNull = Optional.ofNullable(str[5]);

        if (checkNull.isPresent()) {

            String sample = str[5].toUpperCase();

            System.out.print(sample);

        }

        else

            System.out.println("The word is null");

    }

}

Compiling and Executing the above program, shows you the result.

C:\raji\blog>javac OptionalCls1.java

C:\raji\blog>java OptionalCls1

The word is null

These are the way of implementing Optional class in java 8. This can be useful in writing efficient and clean coding.

How to implement Default methods in java8?

     It is one of the features included in java8. A default method is one can be implemented by the interface. If you want to add more implementations further without breaking the existing structure of interface.

It has following features.

  • ·       The method is implemented with some functionality.
  • ·       Even, after the default method implementation, you can add more methods. It is called backward compatibility.
  • ·       Multiple inheritance is possible.
  • There are many ways to use default methods.

Here, we use two types.

A simple way of implementing Dafault method:

  • Create an interface “TstInterface” and add a void method “rectangle” with two arguments (Length and breadth).
  • Write the code for finding area of triangle by the formula (l*b).
  • TstClass is the class which implements the interface.
  • There, include the code for void function implementation.
  • Create an object for class. Call the two functions using objects.

interface TstInterface {

void rectangle(int l,int b);

default void area() {

System.out.println("This program executed Default Method");

}

}

class TstClass implements TstInterface {

public void rectangle(int l,int b) {

System.out.println("The area of rectangle is : "+l * b);

}

public static void main(String args[]) {

TstClass d = new TstClass();

d.rectangle(4,6);

d.area();

}

}

The output is given below.

C:\raji\blog>javac TstClass.java

C:\raji\blog>java TstClass

The area of rectangle is : 24

This program executed Default Method

2.Overriding a Default method:

              Overriding is a concept of redefining a implementation. Here, two interfaces and 2 methods with same name. both of the interfaces are implemented by  a class.

For overriding, the keyword “super” is used.

//Java Program to Override a defult method

interface Interface1 {

    default void myMethod() {

        System.out.println("This message shows Interface1 implementation");

    }

}

interface Interface2 {

    default void myMethod() {

        System.out.println("This message shows Interface2 implementation");

    }

}

public class MyClass implements Interface1, Interface2 {

    @Override

    public void myMethod() {

        Interface1.super.myMethod();  // or Interface2.super.myMethod();

    }

    public static void main(String[] args) {

        MyClass ob = new MyClass();

        ob.myMethod();  // This will call the overridden method

    }

}

Just compile and run the program, you will get the output.

C:\raji\blog>javac MyClass.java

C:\raji\blog>java MyClass

This message shows Interface1 implementation

These are the ways to implement default methods in java.

Using Method References in java 8 part 2:

     First two method references are explained in part 1. The link is given below.

https://rajeeva84.blogspot.com/2024/09/using-method-references-in-java8-part-1.html

Remaining two types are briefly described below.

3.Instance references of a particular object:

              This method reference deals with a particular object within  the class. To implement this method, use the below code.

        Class  Object = inst:: memberFunction;

 Steps:

  • ·       As a beginning, create an interface “Sample” with a void function abc().
  • ·       Inside the class InstMethodReference, develop the code for Message().
  • ·       In the main function, create an object for the class and using “inst::” to call the instance reference of the object created.

// Java Program to develop instant reference of particular object.

interface Sample {

    void abc();

}

public class InstMethodReference {

    public void Message() {

        System.out.println("This is an instance reference of particular object");

    }

    public static void main(String[] args) {

        InstMethodReference inst = new InstMethodReference();

        Sample s = inst::Message;

        s.abc();

    }

}

After the code completion, just compile and run the code as follows.

C:\raji\blog>javac InstMethodReference.java

C:\raji\blog>java InstMethodReference

This is an instance reference of particular object

 

4.Instance Method References of an Arbitrary Object of a Particular Type:

              This type of method reference deals with arbitrary object.

Steps:

  • ·       Create a class “OtherObjectMethodReference”. Inside main(), create a list “plang” and assign different programming languages.
  • ·       Using foreach method, print the list.

import java.util.Arrays;

import java.util.List;

public class OtherObjectMethodReference {

    public static void main(String[] args) {

        List<String> plang = Arrays.asList("C", "C++", "Java");

        plang.forEach(System.out::println);

    }

}

Final step is compile and run the program.

C:\raji\blog>javac OtherObjectMethodReference.java

C:\raji\blog>java OtherObjectMethodReference

C

C++

Java

These are the ways to implement method references in java8.

Using Method references in java8 -Part 1

             Method reference is a concept in java8. It is simple in format. Generally, it is used when it has objects or primitive data. It is typical lambda expressions.

Method references are categorized into many types listed below.

       1.   Constructor references

       2.   Static references

       3.   Instance references of a particular object

       4.  Instance Method References of an Arbitrary Object of a Particular Type

First two method references are coded with examples.

1.Constructor references:

   A constructor is the first function to be called. Here, the method reference is based on constructor.

A sample java Program to print the message using Constructor Reference is given below.

Steps to follow:

  • ·       First, an interface “MeRefInterface” is created with get method with a String parameter.
  • ·       Create a class MeRefClass and add the definition for constructor with a print function.
  • ·       Now, create a class MeRefConstrutor, use the syntax to implement Constructor reference.
  • o   MeRefInterface myInte = MeRefClass::new;
  • ·       Finally, call the function get to display the output.

#java program to illustrate Constructor Reference:

interface MeRefInterface {

                  MeRefClass get(String s);

              }

              class MeRefClass {

                  MeRefClass(String s) {

                      System.out.println(s);

                  }

              }

              public class MeRefConstructor{

                  public static void main(String[] args) {

                     MeRefInterface myInte = MeRefClass::new;

                      myInte.get("This is sample text by using Constructor Method Reference");

                  }

              }

To compile and execute the file, follow the steps.

C:\raji\blog>javac MeRefConstructor.java

C:\raji\blog>java MeRefConstructor

This is sample text by using Constructor Method Reference

 

2.Static references:

If a method reference is said to be static, it refers a static method. The syntax of the static reference is

Class :: staticMethod

Steps:

  • ·       Create an interface “Message” and declare a method Msg().
  • ·       Now, create a method display() to display the output inside a class “StaticMethodReference”.
  • ·       Inside the main function, write the code for developing object and call the static function display.
  • ·       Call the function Msg by using the object mess.

//Java Program to implement Static References

interface Message {

    void Msg();

}

public class StaticMethodReference {

    public static void display() {

        System.out.println("This is a message from static method.");

    }

    public static void main(String[] args) {

        Message mess = StaticMethodReference::display;

        mess.Msg();

    }

}

Compile and execute the above code. It will give you the output.

C:\raji\blog>javac StaticMethodReference.java

 C:\raji\blog>java StaticMethodReference

This is a message from static method.

These are the ways to implement first two method references. Remaining is in part 2. 

how to implement Parallel streams in Java 8:

    When you want to process the data concurrently across multiple process, what will you do???

Java 8 offers you a concept…

That is “Parallel Streams”.

The common usage of parallel Streams is listed below.

Batch Processing: Reading sensor inputs and log files can be done. These can be concurrently   

                                processed across multiple places.

Data Processing: It deals with large amount of data. It collects large amount of data, process it by

                               streams.

Data Analysis:  This process Analyse the data collected.

Image and video processing: Image and video is processed according to the standard format. It deals

                                                     with image filteration, video layout editing and so on.

Sorting, Searching and aggregation: These are operations on data. It deals with arranging the data in

                                                               specified format for sorting. Searching is a process of finding                                                                     an element. Aggregation deals with combining data together.

Machine learning: This deals with large sets of data involving machine learning algorithms.

Real time data processing: Real time data is processed concurrently.

How to create a Parallel Streams:

              As we know earlier, parallel streams are executed the process parallelly. So, it uses stream to execute this.

  • Here, there are three built in packages are used.
  • Arrays, List and Stream collectors. There are the sub packages from java.util package.
  • Create a class “StreamEg2” and save this file as “StreamEg2.java”.
  • Inside the main function, create a list as Array
  • Next, call Parallel Stream function and using ForEach method, print the value.

#Java Program to create Parallel streams

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;

   public class StreamEg2 {

       public static void main(String[] args) {

             

List<Integer> list = Arrays.asList(1, 2, 3, 4);

list.parallelStream().forEach(System.out::println);

}

}

Executing this, you will get the below output.

These are the ways of using ParallelStreams. These are useful in realtime applications and large data manipulation applications.

How to create a java program to Filtering and mapping a list of integers using Streams.

      Streams are extremely useful in java 8 programming. A Basic introduction about streams in written in separate blog post. The link is given below.

https://www.blogger.com/blog/post/edit/5251857942821229/8634074333115313571

Stream operations:

              Stream operations are of two categories. One is intermediate operations. Another one is terminal operations.

Intermediate operations:

These are operations based on filtering, mapping and sorting data. Some of the functions are listed below.

filter() : Based on a condition, the data is filtered.

map() : Each and every element is transformed using this function.

flatmap() : It is used for nesting purpose.

distinct() : It gives you the unique value.

sorted() :  It sorts the elements.

Terminal operations:

As a name indicated, this is the last operations in stream. It may be the end operation or produce the list.

for each() : This is a statement deals with iterative operations.

collect() : It collects thedata

count() : It returns the number of elements.

anymatch() : Checks the element and finds the match.

reduce() : Combines the element and produce the result.

Java program to Filtering and mapping a list of integers using Streams:

·       As a beginning, create a class “StreamEg”. Save this file as “StreamEg.java”.

·       Next, create a list of numbers using array.

·       Filter the odd numbers separately.

·       Create the square of the number by doubling them.

·       Print the output list.

#Java Program

import java.util.Arrays;

   import java.util.List;

   import java.util.stream.Collectors;

//Create a class “StreamEg”

   public class StreamEg {

       public static void main(String[] args) {

//Create a list of integers and assign the values

           List<Integer> nos = Arrays.asList(11, 12, 13, 14, 15, 16, 17, 18, 19, 20);

           // Filtering odd numbers and square them using stream

           List<Integer> oddSquare = nos.stream()

                                              .filter(n -> n % 2 != 0)

                                              .map(n -> n * n)

                                              .collect(Collectors.toList());

//Print the value of list

           System.out.println(oddSquare);

       }

   }

Once you run the program, you will get the output.

These are the ways of using Streams in java. Enjoy Coding!!!!