Posts

Showing posts from April, 2020

How to set Java Object into JaxBElement ?

How to set Java Object into JaxBElement ? * In JaxBElement we are having setValue(T t) method. this will help us to solve this problem. * java.xml.bind.JAXBElement.setValue() Eg. Lets Use College Class as Bean. MainJaxBElement class as main class to process the College Class. package com.javavirus.jaxbelement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class College{ private int id; private String name; public College(int id, String name) { super(); this.id = id; this.name = name; } public int getId() { return id; } @XmlAttribute public void setId(int id) { this.id = id; } public String getName() { return name; } @XmlElement public void setName(String name) { this.name = name; } @Override public String toString() { return "College [id=" + id + ", name=" + name + "]"...

TypeScript - Interface

TypeScript Interface: * Class can implement multiple interfaces. * Define a interface with method contract. Eg: export interface Coach {     getDailyWorkout(): string; } import { Coach } from "./Coach"; export class GolfCoach implements Coach {     getDailyWorkout(): string {         return "Hit 100 balls at the golf range.";     }  } import { Coach } from "./Coach"; export class CricketCoach implements Coach {     getDailyWorkout(): string {         return "Practice your spin bowling technique.";     } } import { CricketCoach } from "./CricketCoach"; import { GolfCoach } from "./GolfCoach"; import { Coach } from "./Coach"; let myCricketCoach = new CricketCoach(); let myGolfCoach = new GolfCoach(); // declare an array for coaches ... initially empty let theCoaches: Coach[] = []; // add the coaches to the array theCoaches.push(myCricketCoach); theCoaches.pu...

Typescript- Abstract Class

Type Script Abstract Class: * Cant create an instance for abstract class. * Abstract class can also have abstract methods. * Abstract method must be implemented in the concrete class. Eg: export abstract class Shape {     constructor(private _x: number, private _y: number) {     }     public get x(): number {         return this._x;     }     public set x(value: number) {         this._x = value;     }     public get y(): number {         return this._y;     }     public set y(value: number) {         this._y = value;     }     getInfo(): string {         return `x=${this._x}, y=${this._y}`;     }     abstract calculateArea(): number; } import { Shape } from './Shape'; export class Circle extends Shape {     calculateArea(...

TypeScript - Inheritance

Typescript - Inheritance: * Inheritance is the OOP Cocept. * Chile class can extends the parent class object and methods. * Support Abstract classess and overriding. * It supports only single inheritance. * But you can implement multiple interfaces. Eg: Shape.ts export class Shape {     constructor(private _x: number, private _y: number) {     }     public get x(): number {         return this._x;     }     public set x(value: number) {         this._x = value;     }     public get y(): number {         return this._y;     }     public set y(value: number) {         this._y = value;     }     getInfo(): string {         return `x=${this._x}, y=${this._y}`;     } } Circle.ts import { Shape } from './Shape'; export class Circle extends S...

TypeScript - Modules

Typescript Modules: * Module can export classes, functions, variables etc., * Another file can import classes, functions, variables etc., from module. Eg. File : Customer.ts export class Customer{ ... ... } File : Driver.ts import {Customer} from './Customer'; let myCustomer = new Customer("Vinoth", "Kumar"); console.log(myCustomer.firstName); console.log(myCustomer.lastName); {Customer} -> Class Name './Customer' -> Directory & File Name

TypeScript - Shortcut Constructor (Parameter Property)

Parameter Properties: * Typescript offers to create a shortcut to create a constructor. * To avoid boiler plate. Normal Approach: Class Customer{ //Start code private firstName : string; private lastName  : string; constructor(theFirst:string, theLast:string){ this._firstName = theFirst; this._lastName = theLast; } //End code public get firstName(): string(){ return this._firstName; } public set firstName(value: string){ this._firstName = value; } } Shortcut: Class Customer{ //Replace Start code constructor(private _firstName: string, private _lastName: string){ } //Replace End code public get firstName(): string(){ return this._firstName; } public set firstName(value: string){ this._firstName = value; } } Use above both codes: let myCustomer = new Customer("Vinoth", "Kumar"); myCustomer.firstName = "Raj"; console.log(myCustomer.firstName);

TypeScript - What is tsconfig.json ?

There are lot of compiler flags are there, So it is difficult to remember. So lets do it in config file. This config file is called "tsconfig.json" file * Place this file in the root directory. Eg. tsconfig.json: { "compilerOptions":{ "noEmitOnError":true, "target":"es5"; } } Command to auto generate this file with template: tsc --init

TypeScript - Access Modifier & get/set

Access Modifier: private - within the class public - access from anywhere protected - within the class and subclasses. Note: Most of the time if compile time error also, It will generate the file and we can run the file. How to avoid this ? 1. Delete the js file whatever created earlier. using below command. Eg. del Customer.js 2. Use below command to not generate the .js file if any compilation error . Command : tsc -noEmitOnError Customer.ts Accessors: Class Customer{ private firstName : string; private lastName : string; public getFirstName(): string(){ return this.firstName; } public setFirstName(theFirst: string): void { this.firstName : theFirst; } } Using Get/Set: * get/set accessors is only supported in ES5 and higher. * you have to set the compiler flag inorder to compile the code. Syntax to compile: tsc --target ES5 -noEmitOnError Customer.ts Example: Class Customer{ private _firstName: string; private _lastName: strin...

Type Script - Class

Create a Class: FileName: *.ts Class Customer{ firstName : string; lastName  : string; constructor(theFirst:string, theLast:string){ this.firstName = theFirst; this.lastName = theLast; } } Lets use class, let mycustomer = new Customer("Vinoth", "Kumar"); console.log(mycustomer.firstName);

TypeScript - Loops & Arrays

Creating Loops & Arrays: * Loop is used to iterate some values. Eg 1. for (let i=0; i < 5; i++) {     console.log(i); } Eg.2: Find the average from the integer array. let reviews: number[] = [5, 5, 4.5, 1, 3]; let total: number = 0; for (let i=0; i < reviews.length; i++) {     console.log(reviews[i]);     total += reviews[i]; } let average: number = total / reviews.length; console.log("Review average = " + average); * Array is Growable in Typescript. Eg.1 let sportsTwo: string[] = ["Golf", "Cricket", "Tennis"]; sportsTwo.push("Baseball"); sportsTwo.push("Futbol"); for (let tempSport of sportsTwo) {     console.log(tempSport); }

TypeScript - let & backticks

What is let: * Its like Javascript var keyword; * In var keyword in javascript have some gotchas and pitfalls like scoping, capturing etc., * let keyword is solving those issues as well. Typescript strongly Typed: let found: boolean = true; found = 0; // Compile time error will throw if you assign 0. mismatch the datatype. let data: any = 50.0; data = "Vinoth"; // true data = false; // true Try to avoid use any, because we will lose type safty. Use backticks: console.log("Hi " + firstname + " " + lastname); console.log('Hi ${firstname} ${lastname}');

TypeScript - Variable

Variable : Syntax : let <variablename>: <type> = <Initial value> ; Eg. let found: boolean = true; let grade: number = 88.6; let firstname: string = 'Vinoth'; let lastname: string = "Kumar";

TypeScript - DataTypes

DataTypes: * boolean - true/false. * number - support integer/floating. * String - text data. * any - its supports any data type. * etc.,

Angular - TypeScript

What is TypeScript: * It support OOP. * It provides static support to Javascript. * Easier to use Javascript. * It is the superset of Javascript & ECMAScript. * Typescript file save as .ts Compile the code: * Typescript have to convert into Javascript. This process is called "transpiling". * demo.ts to demo.js * Command to compile : tsc demo.ts Run the code: * We will use node command to run the code. * Command to run : node demo.js

Angular - Install Guide for Visual Studio, Node (npm), TypeScript (tsc)

UI Tool : https://code.visualstudio.com/download Use Above link to download the VisualStudio and install it. Install Node: * Node is the runtime Environment for executing JavaScript code from the command-line. Steps: 1. Download the node using this link : https://nodejs.org/en/download/current/ 2. Select the Windows Installer (.msi) for your system (32-bit or 64-bit) 3. Run the Installer 4. Follow the steps in the Installer 5. Open a Command Prompt window to verify the node installation 6. In the Command Prompt window, type the following command: node --version If the installation is successful, you will see the version number Note: The Node installation also includes npm (Node Package Manager). 7. Verify npm is installed npm --version If the installation is successful, you will see the version number. Note: node will have a different number than npm. This is similar to a different Java JDK version number compared to Maven version number. Note: In this e...

Angular

Angular: Angular is the framework to build the modern single page application. What is Single page application? * Based on user actions, the application page is updated. * Normally perform partial update, instead of loading full page using REST API. Eg. Google Maps, Gmail etc., Who is Using ? * Citi Bank Customer service. * Australian Immigration etc., Tools & Softwares required to develop, 1. Visual Studio - UI 2. Node 3. TSC

GitLab

Pipeline: * Group of jobs executed in Stages. * All of the jobs executed in parallel in stage. * if all jobs succeed, pipeline move to next stage. * if any one job failed, next stage is not executed. Types of Pipeline: * CI Pipeline build and test stages defined (.gitlab-ci.yml) * Deploy Pipeline: define in .gitlab-ci.yml. Flow of deploying code to server thru various stages. * Project Pipeline: Specially for microservices. Cross project CI depencies, triggered via API. GitLab Architecture: * GitLab Server and atleast one GitLab Runner. * Runner is the one will start the job. * Project Setting -CICD - * GitLab Runner is automatically provided by GitLab Server. * We can also configured our own runners. Why GITLab CI: * Simple Architecture * Docker first approach. * Pipeline as code. * Merge request with CI support. Eg. Build file location: /builds/kumarvinothjoseph/spring-boot-integration-watch-directory/target/spring-integration-moni...

Spring Integration Using DSL - Folder Monitor or Watch Program

Spring Integration: Spring integration is used to enable lightweight messaging system. It supports integration with multiple external system using adapters. DSL - It is helpful to spring integration to configure some builders and fluent API's. IntegrationFlow - It is used to hanlde Multiple different adapter control. Files.inboundAdapter - It is used to build a file reading message source. filter - It is used to check some filter or condition. Poller.fixedDelay - It is used to do the periodic trigger transform - It is a mechanism to convert message payloads from one form to another form between channels. handle - Used to do some operation with another class. Dependencies: <dependencies>     <dependency>       <groupId>org.springframework.boot</groupId>       <artifactId>spring-boot-starter-integration</artifactId>     </dependency>     <dependency>   ...

Java 8 - Date & Time API (Joda-Time API)

Date & Time API (Joda-Time API): * This is developed by joda.org. * java.time is the package name. //imprt java.time.*; v1.7: Date, Calender, TimeStamp etc., - Lot of methods are not preferred to use. v1.8: LocalDate date = LocalDate.now(); // Current System Date YYYY-MM-DD LocalTime time = LocalTime.now(); // Current System Time HH:mm:ss:nnn       -nano second Eg : 2020-04-13 int dd = date.getDayOfMonth();  // 13 int mm = date.getMonthValue();  // 04 int yyyy = date.getYear();  // 2020 Convert 13-07-2020 System.out.printf("%d-%d-%d",dd,mm,yyyy);   //printf Eg: 10:30:50: int h = time.getHour(); // 10 int m = time.getMinute(); //30 int s = time.getSecond(); // 50 int n = time.getNano(); // System.out.printf("%d:%d:%d:%d",h,m,s,n);   //printf Date & Time : LocalDateTime dt = LocalDateTime.now();   // 2020-04-13T10:30:50:324 To get each seperatly we can use the same method which we use ...

Java 8 - Methods in Streams API

Methods in Stream: 1. collect() It is used to collect element from the stream and add the object into specified collection. 2. count() It is used to count the element from the stream and return the count. long count = l.stream().map(I -> I*2).count(); 3. sorted() * Used to sort the element from the stream. * Default sorting & our own custom sorting. Types: a. sorted -> Default sorting order. Eg. List<Integer> l2 = l.stream().sorted().collect(Collectors.toList()); b. sorted(Comparator c) -> Custom sorting order Eg. List<Integer> l2 = l.stream().sorted((i1, i2) -> -i1.compareTo(i2)).collect(Collectors.toList()); when you using (-) then reverse sorting. 4. min() & max() Note: Please sort the collection before using this. min(): * If you want to take the min value from the collection then you have to go for this. Eg. Integer min = l.stream().min((i1,i2) -> i1.compareTo(i2)).get(); System.out.println(min);...

Java 8 - Streams API

Streams API: * stream() method present inside collection interface as default method. * Stream is a interface present in java.util.stream package. * Stream s = c.stream(); // c - any collection object Use of Stream: * If you want to perform some operation in collection, then will go for Steams. Filter: * If you want to filter the collection object based on some boolean condition, then we have to go for this. public stream filter(Predicate<T> t){ } Processing stream involved in 2 steps, 1. Configureation a. filter  - If you want to filter the collection object then we have to go for this. b. map - If you want to perform some operation using this all values, then we have to go for this. 2. Processing How to use, Print Even Numbers: ArrayList<Integer> l = new ArrayList<>(); l.add(0); l.add(5); l.add(10); l.add(15); l.add(20); l.add(25); Example 1:  For Filter * If you want to filter the collection object based on some boolean ...

Collection VS Streams in Java 8

Collection: * Group of object as a single entity, then will go for collection. Stream: * If you want to process object from the collection, then will for stream.

Java 8 - Constructor Reference By using :: (Double Colon) Operator

Constructor Reference By using :: (Double Colon) Operator: Rule: * Constructor and method argument should be match. * It will return Sample object, this is my expectation. interface Interf{ public Sample get(); } Class Sample{ Sample(){ System.out.println("Sample constructor"); } } Using Lambda: Class Test{ public static void main(String args[]){ Interf i = () -> { Sample s = new Sample(); return s; }; Sample s = i.get(); } } Using Constructor :: Class Test{ public static void main(String args[]){ Interf i = Sample :: new;    // Use this constructor. Sample s = i.get(); } }

Java 8 - Method Reference By using :: (Double Colon) Operator

Method Reference By using :: (Double Colon) Operator: * Instead of Lambda Expression we can go for Method Reference. * We are not required to provide any new implementation, just we want to refer another method. * It is used for Code reusability. - Benefit Rule: * Both methods should have same argument types. * See Below example in m1() & m2() Eg. interface Interf{ public void m1(); } Static method example: Syntax:  Classname::methodName Example Program: Class Test{ public static void m2(){ System.out.println("method reference"); } public static void main(String args[]){ Interf i = Test::m2; i.m1(); } } // M1 want to refer M2(Static method) Instance method example: Syntax: ObjectReference::methodName Example Program: Class Test{ public static void m2(){ System.out.println("method reference"); } public static void main(String args[]){ Test t = new Test(); Interf i = t::m2; i.m1(); } } Lambda vs ...

Java 8 - Binary Operator & Primitive Versions

Binary Operator & Primitive Versions: Function<T,R> - 1 input argument. input and output both are different type of object. Unary Operator<T> - input and output both are same type of object BiFunction<T,U,R> - 2 input argument Binary Operator<T>    - input and output all 3 are same type of object. Syntax: BinaryOperator<T>  public T apply(T,T) BiFunction Example: class Test { public static void main(String[] args) { BiFunction<String,String,String> f=(s1,s2)->s1+s2; System.out.println(f.apply("durga","software")); } } Binary Example: class Test { public static void main(String[] args) { BinaryOperator<String> b=(s1,s2)->s1+s2; System.out.println(b.apply("durga","software")); } } Primitive versions of Binary Operator: 1. IntBinaryOperator public int applyAsInt(int i,int j) 2. LongBinaryOperator public long applyAsLong(long l1,long l2) 3. DoubleBi...

Java 8 - Unary Operator & Primitive Versions

Unary Operator & Primitive Versions: * If input and output both are same object then we should go for unary operator. * It is the child of function. eg. Function<Integer, Integer> f = i -> i * i;  - Dont go for function. Because input & output both are Integer. Syntax: interface UnaryOperator<T> { public T apply(T t); } Example: class Test { public static void main(String[] args) { UnaryOperator<Integer> f=i->i*i; System.out.println(f.apply(6)); } } Primitive Versions  of Unary Operator: 1. IntUnaryOperator:  public int applyAsInt(int) 2. LongUnaryOperator:  public long applyAsLong(long) 3. DoubleUnaryOperator:  public double applyAsDouble(double) Example: class Test { public static void main(String[] args) { IntUnaryOperator f=i->i*i; System.out.println(f.applyAsInt(6)); } }

Java 8 - Primitive type Functional Interface for Supplier

Primitive type Functional Interface for Supplier: 1. IntSupplier public int getAsInt(); 2. LongSupplier public long getAsLong() 3. DoubleSupplier public double getAsDouble() 4. BooleanSupplier public boolean getAsBoolean() class Test { public static void main(String[] args) { IntSupplier s=()->(int)(Math.random()*10); String otp=""; for(int i =0;i<6;i++) { otp=otp+s.getAsInt(); } System.out.println("The 6 digit OTP: "+otp); } } Output: The 6 digit OTP: 035716

Java 8 - Primitive type Functional Interface for Consumer

Primitive type Functional Interface for Consumer: 1. IntConsumer public void accept(int value) 2. LongConsumer public void accept(long value) 3. DoubleConsumer public void accept(double value) 4. ObjIntConsumer<T> public void accept(T t,int value) 5. ObjLongConsumer<T> public void accept(T t,long value) 6. ObjDoubleConsumer<T> public void accept(T t,double value) Example: class Test { public static void main(String[] args) { IntConsumer c= i->System.out.println("The Square of i:"+(i*i)); c.accept(10); } } Output: The Square of i:100

Java 8 - Primitive Type Functional Interface for Function

Primitive Type Functional Interface for Function: Drawback Program: Function<Integer, Integer> f = i -> i*i; System.out.println(f.apply(5));  // primitive type convertion will happend to run the above step. (So Autoboxing and Auto Unboxing will be happend) Functions are , 1. IntFunction : can take int type as input and return any type public R apply(int i); 2. LongFunction : can take long type as input and return any type public R apply(long i); 3. DoubleFunction : can take double type as input and return any type public R apply(double d); 4. ToIntFunction : It can take any type as input but always returns int type public int applyAsInt(T t) 5. ToLongFunction : It can take any type as input but always returns long type public long applyAsLong(T t) 6. ToDoubleFunction : It can take any type as input but always returns double type public int applyAsDouble(T t) 7. IntToLongFunction : It can take int type as input and returns long type public long...

Java 8 - primitive Functional interfaces for Predicate

The following are various primitive Functional interfaces for Predicate. 1.IntPredicate-->always accepts input value of int type 2.LongPredicate-->always accepts input value of long type 3.DoublePredicate-->always accepts input value of double type interface IntPredicate { public boolean test(int i); //default methods: and(),or(),negate() } interface LongPredicate { public boolean test(long l); //default methods: and(),or(),negate() } interface DoublePredicate { public boolean test(double d); //default methods: and(),or(),negate() } Example: class Test { public static void main(String[] args) { int[] x ={0,5,10,15,20,25}; IntPredicate p=i->i%2==0; for (int x1 : x) { if(p.test(x1)) { System.out.println(x1); } } } } In the above example, autoboxing and autounboxing won't be performed internally.Hence performance wise improvements are there.

Java 8 - Primitive Type Functional Interface Understanding

Primitive Type Functional Interface: Autoboxing: (After Java v.1.5) Converting primitive data type to object type automatically by compiler, this is called Autoboxing. Eg. Integer i=10; => Integer i = Integer.valueOf(10); (Internally this will happend) Auto Unboxing: Converting object type to primitive data type automatically by compiler, this is called Auto Unboxing. Eg. Integer I = new Integer(10); int x=I; (After Java v.1.5) Generics Type Parameter: ArrayList<Integer> al = new ArrayList<Integer>(); Integer - type parameter ArrayList<int> al = new ArrayList<int>(); - Not Valid For the type parameter only object types are allowed. Primitives not allowed to pass. Primitive Type Functional Interface for Predict: Drawback program: Eg. Print Even numbers 1. int[] = {0,5,10,15,20,25,30}; 2. Predicate<Integer> p = i -> i%2==0; // Step2:i%2 can't happend with Object value, So it has to convert into primitive (Auto Unboxing) 3. fo...

Java 8 - OneArgument VS TwoArgument Predefined Functional Interface

Image

Java 8 - BiConsumer

BiConsumer: * When we need to access two input argument and we need to return some values, then we need to go for BiConsumer. Syntax:  interface BiConsumer<T,U> { public void accept(T t,U u); //default method andThen() } Example: To increment employee Salary class Employee { String name; double salary; Employee(String name,double salary) { this.name=name; this.salary=salary; } } class Test { public static void main(String[] args) { ArrayList<Employee> l= new ArrayList<Employee>(); populate(l); BiConsumer<Employee,Double> c=(e,d)->e.salary=e.salary+d; for(Employee e:l) { c.accept(e,500.0); } for(Employee e:l) { System.out.println("Employee Name:"+e.name); System.out.println("Employee Salary:"+e.salary); System.out.println(); } } public static void populate(ArrayList<Employee> l) { l.add(new Employee("Durga",1000)); l.add(new Employee("Su...

Java 8 - Bi Function

Bi Function: * When we need to access two input argument and we need to return some values, then we need to go for BiFunction. Syntax: interface BiFunction<T,U,R> { public R apply(T t,U u); //default method andThen() } Example: class Test { public static void main(String[] args) { BiFunction<Integer,Integer,Integer> f=(a,b)->a*b; System.out.println(f.apply(10,20)); System.out.println(f.apply(100,200)); } } Example: Create Student Object by taking name, roll no as input class Student { String name; int rollno; Student(String name,int rollno) { this.name=name; this.rollno=rollno; } } class Test { public static void main(String[] args) { ArrayList<Student> l = new ArrayList<Student>(); BiFunction<String,Integer,Student> f=(name,rollno)->new Student(name,rollno); l.add(f.apply("Durga",100)); l.add(f.apply("Ravi",200)); l.add(f.apply("Shiva",300)); l.add(f.apply(...

Java 8 - Bi Predicate

Bi Predicate: * When we need to access two input argument and we need to do some check condition, then we need to go for BiPredicate. Syntax: interface BiPredicate<T1,T2> { public boolean test(T1 t1,T2 t2); //remaining default methods: and(), or() , negate() } Example: class Test { public static void main(String[] args) { BiPredicate<Integer,Integer> p=(a,b)->(a+b) %2==0; System.out.println(p.test(10,20)); System.out.println(p.test(15,20)); } } output: true false

Java 8 - Two Argument(Bi) Functional Interfaces

Two Argument(Bi) Functional Interfaces - BiPredicate, BiFunction and BiConsumer * Predicate, Function and Consumer can access only one input values. * BiPredicate can access two input values. * BiFunction can access two input values. * BiConsumer can access two input values.

Java 8 - Comparison Table of Predicate, Function, Consumer and Supplier

Image

Java 8 - Predefined Functional Interface - Supplier

Predefined Functional Interface - Supplier * I wont provide any input, But I need some output based on some operation. * Eg. Provide some random value, Get student details etc., Syntax: interface Supplier<R> { public R get(); } Eg: Supplier to supply System Date class Test { public static void main(String[] args) { Supplier<Date> s=()->new Date(); System.out.println(s.get()); System.out.println(s.get()); System.out.println(s.get()); }  }  Output: Sun Aug 05 21:34:06 IST 2018 Sun Aug 05 21:34:06 IST 2018 Sun Aug 05 21:34:06 IST 2018 Eg: Supplier to supply Random Passwords Rules: 1. length should be 8 characters 2. 2,4,6,8 places only digits 3. 1,3,5,7 only Capital Uppercase characters,@,#,$  class Test { public static void main(String[] args) { Supplier<String> s=()-> { String symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ#$@"; Supplier<Integer> d=()->(int)(Math.random()*10)...

Java 8 - Predefined Functional Interface - Consumer

Predefined Functional Interface - Consumer * If we no need of any return,then we will go for consumer. interface Consumer<T> { public void accept(T t); } accept() - abstract method andThen() - default method Eg: class Test { public static void main(String[] args) { Consumer<String> c=s->System.out.println(s); c.accept("Hello"); c.accept("DURGASOFT"); } } Output: Hello DURGASOFT Eg: Display Movie Information class Movie { String name; String hero; String heroine; Movie(String name,String hero,String heroine) { this.name=name; this.hero=hero; this.heroine=heroine; } } class Test { public static void main(String[] args) { ArrayList<Movie> l= new ArrayList<Movie>(); populate(l); Consumer<Movie> c= m->{ System.out.println("Movie Name:"+m.name); System.out.println("Movie Hero:"+m.hero); System.out.println("Movie Heroine:"+m.h...

Java 8 - Example Program for Predicate, Function & Consumer

Example Program Predicate, Function & Consumer: class Student { String name; int marks; Student(String name,int marks) { this.name=name; this.marks=marks; } } class Test { public static void main(String[] args) { ArrayList<Student> l= new ArrayList<Student>(); populate(l); Predicate<Student> p= s->s.marks>=60; Function<Student,String> f=s->{ int marks=s.marks; if(marks>=80) { return "A[Dictinction]"; } else if(marks>=60) { return "B[First Class]"; } else if(marks>=50) { return "C[Second Class]"; } else if(marks>=35) { return "D[Third Class]"; } else { return "E[Failed]"; } }; Consumer<Student> c=s->{ System.out.println("Student Name:"+s.name); System.out.println("Student Marks:"+s.marks); System...

java 8 - Predefined Functional Interface - Function Examples

Eg: Remove spaces in the string class Test { public static void main(String[] args) { String s="CTS is one of the MNC"; Function<String,String> f= s1->s1.replaceAll(" ",""); System.out.println(f.apply(s)); } } Eg: Number of spaces present is the given string class Test { public static void main(String[] args) { String s="durga software solutions hyderabad "; Function<String,Integer> f= s1->s1.length() - s1.replaceAll(" ","").length(); System.out.println(f.apply(s)); }  } Write Program to find total Monthly salary of all employees using function: class Employee { String name; double salary; Employee(String name,double salary) { this.name=name; this.salary=salary; } public String toString() { return name+":"+salary; } } class Test { public static void main(String[] args) { ArrayList<Employee> ...

Java 8 - Predefined Functional Interface - Function

Predefined Functional Interface - Function: * Function will process something and can return anything. Interface: interface function(T,R) { public R apply(T t); } T - Input type R - Return type Methods: apply() - abstract method andThen() - default method compose() - default method identity() - static method

Java 8 - Predicate VS Function

Predicate : * To implement condition check and return true or false. * Predicate<T> - It is can take one input parameter. * Predicate interface contain test() * public boolean test(T t) Function: * To implement some operation and return some values. * Function<T,R> - T - Input type, R - Return type. * Function interface contain apply() * public R apply(T t) Program using both: class Employee { String name; double salary; Employee(String name,double salary) { this.name=name; this.salary=salary; } public String toString() { return name+":"+salary; } } class Test { public static void main(String[] args) { ArrayList<Employee> l= new ArrayList<Employee>(); populate(l); System.out.println("Before Increment:"); System.out.println(l); Predicate<Employee> p=e->e.salary<3500; Function<Employee,Employee> f=e->{ e.salary=e.salary+477; return e; }; System.out....

Java 8 - Predefined Functional Interface - Predicate - Example

Predefined Functional Interface - Predicate: * Performed some conditional check and produce the output as true or false ? * Predicate is a boolean value function. eg. check employee salary >10000000 or not * Predicate contain the only one abstract method. method is: test() interface Predicate<T> { boolean test(T t); } How to use this in our application: Case 1: Integer Check public boolean test(Integer I){ if(I >10){ return true; }else{ return false; } } Using Lambda : (Integer I) -> { if(I >10) return true; else return false; } or I -> I >10; Final Code: Predicate<Integer> p = I -> I >10; System.out.println (p.test(100)); // true System.out.println (p.test(5)); // false Example Program: import java.util.function.*;   // import java.util.function.Predicate; Class Test{ public static void main(String args[]){ Predicate<Integer> p = I -> I >10; System.out.println (p.test(100)...