Friday, September 21, 2018

java 11 features - Default Collection Method toArray(IntFunction) example

In this blog post, We are going to learn the Java 11 features - toArray(IntFunction) method.
java 11 features - Default Collection Method toArray(IntFunction) example

Default Collection Method - toArray(IntFunction)

With Java 11 version, New default method toArray(IntFunction) is added in java.util.collection interface. You can check my previous on default method.This is used to return Array from a collection of objects dynamically. During development, Developer need to convert Collection to Array types, This will ease and simplify the developer life 
Signature

    default <T> T[] toArray(IntFunction<T[]> generator) {
        return toArray(generator.apply(0));
    }
 
This takes input as IntFunction - Functional interface which contains only one abstract method.

ToArray(IntFunction) Example

This example covers the following things

  • How to Convert List of Strings to Array of Strings 
  • How to Convert Set of Strings to Array of Strings 

List.of() and Set.of() methods introduced in Java 10 features  to create Unmodified collections
import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class DefaultMethod {
 public static void main(String[] args) {
  final List<String> numbersList = List.of("One", "Two", "Three", "Four");  
  System.out.println(Arrays.toString(numbersList.toArray(String[]::new)));  
  final Set<String> setStrings = Set.of("Kiran", "John", "Frank", "Sai");  
  System.out.println(Arrays.toString(setStrings.toArray(String[]::new)));  

 }
}
Output is
[One, Two, Three, Four]
[Sai, John, Frank, Kiran]

Collection existing ToArray Methods

Collection interface has already toArray() method, Compiler unable to decide when a null object is passed gives compile error The method toArray(Object[]) is ambiguous for the type Set. The reason is compiler get ambiguous to choose from toArray(Object[]) and toArray(IntFunction[]) methods. Instead of null,caste null like toArray((Object[])null). NullPointerException is always thrown for both of the methods.

Collection interface has following overloaded methods, toArray(IntFunction) method is the default method and remaining methods are not.

    default <T> T[] toArray(IntFunction<T[]> generator) {
        return toArray(generator.apply(0));
    }
    <T> T[] toArray(T[] a);
    Object[] toArray();

Typescript Beginner Guide to Decorators basics with examples

Typescript Decorators examples

Typescript Decorators

Typescript introduced decorators, Decorators is a one of a design pattern in an object-oriented program.

Decorator Design pattern

Design patterns are solutions to repeated problemsn. This pattern allows adding functions and behavior to objects dynamically. This will not affect the overall behavior of objects of a class.

Typescript decorators can be applied to 
  • Methods
  • Classes
  • Properties
  • parameters
  • Accessor
These are experimental features, This might change in future versions. This will not be available to code normally.

We have to doCompilerpoiler configurations - experimentalDecorators to enable it.

This can be done via command line or tsconfig.json.

tsc --target ES5 --experimentalDecorators
{
    "compilerOptions": {
        "target": "ES5",
        "experimentalDecorators": true
    }
}
We will see the decorator examples in future posts
Class Decorator and Examples

Thursday, September 20, 2018

Primeng -Learn Angular Progressbar Example

In this blog post, We are going to learn Primeng Angular Progressbar tutorials with example.
Primeng is Rich UI library for providing rich ui components of an Angular framework. It Provides progress bar UI Component.

Angular Progressbar Component example 

progressbar is a UI component is used to indicate the progressive state of an event or action. For example, This will be shown to the user about status during the upload of a file to a server. This will be given the status of the file upload status to the user. Primeng provides Horizontal progress status of an action. It gives progress status to the user during below operations.

  • File upload status
  • Backend Database processing 
  • REST API Operations

This will be very helpful for user experience

. First, We need to create an Angular application using Angular CLI tool and Next is Install it and configure it in your application. You can check below articles about creation and installation in the application.
This post will not talk about creating an application and install Primeng framework into the angular application. The below code works on Angular 4 / Angular 5/Angular 6 versions. Latest Primeng Version is preferable.

Import ProgressBar Module into Application

It provides every component in the form of a module. To use this component, Import module In the application module.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule} from '@angular/platform-browser/animations'; 
import {ProgressBarModule} from 'primeng/progressbar';
import {GrowlModule} from 'primeng/growl';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    ProgressBarModule, // Progress Bar support
    GrowlModule
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas:
        [CUSTOM_ELEMENTS_SCHEMA]

})
export class AppModule { }

Static Progress bar

Progress Bar value is fixed. It will show some percentage of the total status of the progress bar
<p-progressBar [value]="90"></p-progressBar>
You can see the output as below
primeng Angular Progressbar Static example

Dynamic Progress bar 

Emit values for every 100 milliseconds from 1 to 100 values.
Generate the Timer using rxjs Interval operations
Emit the values from 1 to 100  using take rxjs Operators.
the emit values are subscribed  and binding to progress bar

app.component.ts

import { Component, OnInit } from '@angular/core';
import {Message, MessageService} from 'primeng/api';
import { interval, Subscription } from 'rxjs';
import { take } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  outputMsg: Message[];

  statusNum: number = 0;
  subscription$: Subscription;

  constructor(){
  }
  ngOnInit() {
    const interval$ = interval(10);
    const timer = interval$.pipe(take(100));
    this.subscription$ = timer.subscribe(
      val =>{this.statusNum = val + 1;
      console.log(this.statusNum)},
      () => { },
      () => this.outputMsg = [{severity: 'success', summary: 'Success', detail: 'Tasks Done'}]);
    
}
}
Html Template Changes


app.component.html
<div style="text-align:center">
   <h1>
    Primeng Angular ProgressBar Component Example
</h1>
</div>
<p-growl [value]="outputMsg"></p-growl>

<div style="text-align:center">
    <p-progressBar [value]="statusNum"></p-progressBar>
</div>
And output is
primeng Angular Progressbar dynamic example

indeterminate progress bar 

There are two types of modes of progress bars we can configure.
indeterminate
This shows a progress bar of a operation continuously ie indeterminate times. For example, Loading One lack records from Excel to Database. It shows the status bar continuously until data is completely loaded. Once data is finished loading, It will not show status bar
determinate 
This shows estimated status of the operation over a total operation status. For example, Two loads one lack records, It shows the progress like 10% status to end user if 10000 records are loaded. It will show the status until it reaches 100%.
modes:- indeterminate or determinate
<p-progressBar mode="indeterminate" [style]="{'height': '20px'}"></p-progressBar>

and output is
primeng Angular Progressbar indeterminate example

Wednesday, September 19, 2018

Primeng Autocomplete Angular tutorial with examples

In this blog post, We are going to learn Implement Autocomplete feature of Primeng in Angular with an example.

Angular Autocomplete Component 

Autocomplete is a User interface feature and it contains an Input text box and allows the developer to type text, and application display the matched words results for typed characters and give complete word prediction list. It is an easy way to select the text from the user text box. This is a basic UI element on every UI framework provides. Primeng also provides as an angular component.

Angular Application Example

First, create an angular application using Angular CLI. You can check my previous post of Angular application generation from scratch and also about Primeng Integration example of Angular. This article does not talk about the angular application structure and primeng integration. Please find below other tutorials of Primeng.
This article code works on angular 4/5/6 versions. The latest Angular version is preferable for Primeng framework.

Import AutoCompleteModule module

Primeng provides autocomplete feature AutoCompleteModule. So you have to import this module in your application module. In-app module file, Import autocomplete module and configure Imports section of NgModule configuration
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule} from '@angular/platform-browser/animations'; 
import {AutoCompleteModule} from 'primeng/autocomplete';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AutoCompleteModule, // autocomplete support
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas:
        [CUSTOM_ELEMENTS_SCHEMA]

})
export class AppModule { }

Application Component Configuration -app.component.ts  

In Application Component, Need to provide data as well as method or function that checks against typed keyword
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  numbers: string[] = ['onne','two','three','four','five','six','seven','eight','nine','ten'];
  output: string[];
  constructor(){

  }
  search(event) {
    console.log('event',event);
    this.output = this.numbers.filter(c => c.startsWith(event.query));
}
}

Template HTML Changes - app.component.html

 In the template HTML changes, Configured two-way binding using ngModel attribute And also added suggestions attribute for list of suggestions for typed query CompleteMethod method will be fired when the user typed a key and it has a parameter of the event. query parameters which contain the typed keyword. This method returns the matched query list of content and updates to suggestions binding
<div style="text-align:center">
   <h1>
      Primeng Angular AutoComplete Demo
   </h1>
</div>
<div style="text-align:center">
    <p-autoComplete [(ngModel)]="selectNumber" [suggestions]="output" (completeMethod)="search($event)"
    placeholder="Search" [dropdown]="true" ></p-autoComplete>
</div>
Output
primeng angular autocomplete example

Dropdown Attribute 

By default, This is set to false. It displays a button next to textbox when dropdown=true. You can check output of configuring dropdown property
Angular Primeng Autocomplete dropdown example

Multiple values select 

Multiple values can be selected by setting multiple properties to true. Two-way binding module also should be a String array instead of a single string. selectNumber: string[]; instead of selectNumber: string;
    <p-autoComplete [(ngModel)]="selectNumber" [suggestions]="output" (completeMethod)="search($event)"
 placeholder="Search" [dropdown]="true" [multiple]="true" ></p-autoComplete>
Please see the output of the above
primeng angular autocomplete multiple values select

Objects and ng-template Example 

As of now, saw an example how simple strings can be populated. We can also populate Object binding using field property In the Object, We have id, name and department fields. The object is matched with name field with typed word. Field defines the label of the object that needs to display. ng-template tag allows the component to display custom content. In this example displaying name and department as the custom template 
app.component.ts
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  employee:any;
  employees = [
    {"id": 1, "name": "kiran", "department": "Account"},
    {"id": 2, "name": "john", "department": "Sales"},
    {"id": 3, "name": "frank", "department": "Hr"},
  ];
  employeesResult: Array = [];  
  constructor(){
  }
  searchEmps(event): void {
    this.employeesResult = this.employees.filter(c => c.name.startsWith(event.query));

 }
}
app.component.html
<div style="text-align:center">
   <h1>
      Primeng Angular AutoComplete Object Demo
   </h1>
</div>
<div style="text-align:center">
    <p-autoComplete [(ngModel)]="employee" [suggestions]="employeesResult" (completeMethod)="searchEmps($event)" field="name">
        <ng-template let-employee pTemplate="item">
          {{employee.name}} {{employee.department}}
        </ng-template>
        <ng-template let-employee pTemplate="selectedItem">
            {{employee.name}} {{employee.department}}
        </ng-template>
      </p-autoComplete>

</div>
You can check the output
angular primeng autocomplete object example

Sunday, September 16, 2018

Typescript - Static keyword with Property,method,Constructor examples

In this blog post, We are going to learn Static keyword with properties, methods, and constructor of a class in typescript.
Typescript - Static keyword with Property,method,Constructor examples

Static keyword

static is a keyword which can be applied to properties and methods of a class. Static members are accessed using directly using class names.

static properties and Method example

When you want to call any methods in a class, we will use object instance for accessing it methods, Static methods will use class names
In the class,
  • Declared static variable and nonstatic variable
  • Declared static method and nonstatic method
  • static methods and properties are accessed using class names
  • nonstatic methods and variables are accessed using an instance of a class ie object.
It gives compilation error for below cases
  • calling a static method with an object or instance names
  • calling non-static method with class names
class MyClass {
    static staticVariable: number = 0;
    nonStaticVariable: number = 0;
    constructor() {
        console.log("constructor");
    }
    nonStaticMethod() {
        console.log("non static method")
    }
    static staticMethod() {
        console.log("Static method")
    }
}

MyClass.staticMethod(); // This works fine
let myclass1 = new MyClass(); 
myclass1.nonStaticMethod() // This works fine

myclass1.staticMethod() // Compilation Error
MyClass.nonStaticMethod()  // Compilation Error

Static Constructor

 when the static keyword is applied to the constructor, Compiler gives compilation error 'Static modifier cannot appear on a construct declaration'. In a Typescript, static keyword is not applied to a Class constructor.
class ClassDemo {
    msg: string;
    static constructor(msg: string) {
        this.msg = message;
    }
    hello() {
        return "Hello, " + this.msg;
    }
}
let classDemo = new ClassDemo("world");

Example 

We can write a static keyword in different way using static method. Declare static initialization method which will initialize data

class ClassDemo {
    static msg: string;
    constructor() { 
    }
    static construct() {
        this.msg="static typescript example"
        console.log('construct static method')
    }
}
console.log(ClassDemo.construct)

Tuesday, September 11, 2018

Typescript - Object Type and Object with examples

In this blog post, We are going to learn the typescript object type with examples.
Typescript - Object Type and Object with examples

In the typescript, the object has three variations of creating objects.

1. Object
2. object
3. {}

Typescript object type 

Typescript introduced a new data type called object type. this object represents types which are not primitive types like string, number, void, boolean, null and defined.
The reason to introduce to other object type is as follows

Below Javascript Object class has methods which take an object as a parameter. In Typescript, there is non-primitive type representation for this methods. object type is introduced.

Object.getOwnPropertyDescriptor
Object.create
Object.observe
passing primitive values to the above methods throws at runtime. Typescript gives compilation error because of the object type assertion check
object declaration
const obj: object = {};

Object Class 

This is Object class which is core Superclass for all javascript API classes which contain methods toString and toLocalString

Empty Object -{}

This is a custom object which has an empty object with no variables and methods. Empty Object and Object point to the same type
let myobject = {};
myobject.key = 'test';
In the empty object, there is no key associated, It gives compilation error - Property key does not exist on type{} Object also can be created using predefined properties Here created object of Emp with two properties name and id of type string and number Typescript treat this object as {name:string,id: number} when you assign any values other than of different types, It gives compilation error

Examples

var Emp = {
  name: 'Tom',
  id: 1
};

Emp = {
  name: 'Kiran',
  salary: 2000
};
In the below example, Created object, and now changing object with different values as well as modifying object structure, This gives compilation error as a new object is not assignable to an existing object
The object can be used in many ways like below thing

  • The object contains functions including properties 
  • Can be created using object literals 
  • Can be passed an object to a function 
  • Can also object verified using duck typing means if the two objects contain 1. Same type 2. Same properties

How to check if two objects type equality?

Typescript Reflection API provides a constructor to check object type and returns ClassName Here is an example of checking objects of the same type.
class Parent {}
class Child extends Parent {}
var parent = new Parent();
var child = new Child();
var parent1: Parent;
parent1 = new Child();
console.log(parent.constructor == Parent); // returns true 
console.log(child.constructor == Child); // returns true
console.log(parent1.constructor == Child); // returns true
console.log(parent1.constructor == Parent); // returns false

Typescript let, var, Const keyword with examples | Javascript | ES6

let var, Const keywords are used to declared variables in typescript and javascript. Variables can be declared globally or locally.
Typescript let, var, Const keyword with examples | Javascript | ES6

Var keyword

the var keyword is for a variable declaration of javascript. Typescript behavior also same as the functional scope
  1. Variable declared with this keyword scope is either locally if declared in a function or globally if declared outside 
  2. if the variable is not used var keyword  for declaring a variable, It assumes global variables
  3. the variable is redeclared with var keyword, It will not lose its original value
  4. variable returned undefined without declaring and initialization its value

example and usage

var value = 11;
var value1;
function myfunction() {
    value = 456; //  allowed
    value2 = 14
    console.log(value) // 456
    console.log(value1) // undefined
    console.log(value2) // 14
}
myfunction();

Let Keyword 

 Let keyword introduced ES6 - ES2015, It is used to declare a variable in block scope let keyword with colon defines type annotations
Here is an example of let keyword.
let value = "abc";
console.log(value); // abc
if (true) {
    let value = "newabc";;
    console.log(value); // newabc
}
console.log(value); // abc
Redeclaring same variable with let in the current context throws SyntaxError - Can not redeclare blocked-scope variable value
let value = "abc";
let value = "newabc";

Let variable hosting

when the variable is used without declaring it throws Uncaught ReferenceError: value is not defined
function myfunction() { 
    console.log(value);
}
myfunction()

const keyword 

const keywords same like let and there is the difference. a variable declared with const must be initialized immediately once const variable declared, It values not changed by reassigning new value Example
const value = 123;
function myfunction() {
    value = 123; // not allowed
}

ES6 Let and Const temporal dead zone 

This was introduced in ES6. Calling variable without declaring it using let and const has thrown ReferenceError. This is to avoid the programming exceptions and safeguard for debugging variables

Difference between Let and var keyword

Both are used to declare a variable Let create a variable in blocked scope var creates a variable in global scope Difference example is as below
// example var
for (var val = 0; val < 2; val++){
   console.log(val) 
}
console.log(val) // 5

// example let
for (let val = 0; val < 2; val++){
   console.log(val)
}
console.log(val)// undefined

Monday, September 10, 2018

Typescript Array Sort method with example | javascript

This blog post, We are going to learn how to Sort Array in javascript or typescript.
Typescript Array Sort method with example | javascript

Array Sort method

This method sorts the elements of an array in ascending or descending.
Elements are simple strings, Object which contains key and values or Typescript classes.

Syntax

Array.sort(ComparatorFunction)
Parameters are ComparatorFunction is a function which specifies the order of the elements, If not passed, Default sorting is applied.

Array String sort Example

Array Declared and initialized with new Array() and strings separated in comma No comparator function passed and Array.sort() method is used
var arrayStrings = new Array("one", "two", "there", "four"); 
var sortedArray = arrayStrings.sort(); 
console.log(""+sortedArray );
Output is
four,one,there,two

Object Array Sort Example ascending 

The object can be directly created using an array or you can create an Interface. This Emp object contains id and names This example sort the objects by name property First created Emp interface.
 interface Emp {
     id: number;
     name: string;
}
Next, Create Array of Objects and initialize with values
var emps: Emp[] = [
    { id: "5", name: "Kiran" },
    { id: "1", name: "Frank" },
    { id: "2", name: "Tom" },
    { id: "51", name: "Abc" }
]
And Write a Compare Function for Name of Emp object
var compareName = function (emp1: Emp, emp2: Emp) {
        if (emp1.name > emp2.name) { return -1; }
        if (emp1.name < emp2.name) {return 1; }
        return 0;
    }
 
Finally Call Array.sort() with compare function
var sortedArray = emps.sort(compareName); 
console.log(sortedArray );
Output is
0: {id: "2", name: "Tom"}
1: {id: "5", name: "Kiran"}
2: {id: "1", name: "Frank"}
3: {id: "51", name: "Abc"}

Sort Array Object Data by Date property Example

The object contains key date property. We can sort the object data based on date ascending or descending. Need to supply comparator custom code which handles Date comparisons. First Date string is converted to an Inbuilt Date object.
Date ascending 
This is an example sort array of object date by date ascending
interface Emp {
     id: number;
     name: string;
     date: Date;
}
var emps: Emp[] = [
    { id: "5", name: "Kiran",date:"2018-05-05" },
    { id: "1", name: "Frank",date:"2017-05-05"},
    { id: "2", name: "Tom",date:"2016-05-05" },
    { id: "51", name: "Abc" ,date:"2018-10-05"}
]

var compareDate = function (emp1: Emp, emp2: Emp) {
    var emp1Date = new Date(emp1.date).getTime();
    var emp2Date = new Date(emp2.date).getTime();
    return emp1Date > emp2Date ? 1 : -1;  
}
var sortedArray = emps.sort(compareDate); 
console.log(sortedArray );
Output is

0: {id: "2", name: "Tom", date: "2016-05-05"}
1: {id: "1", name: "Frank", date: "2017-05-05"}
2: {id: "5", name: "Kiran", date: "2018-05-05"}
3: {id: "51", name: "Abc", date: "2018-10-05"}
We will see the Sort Date by descending.
Date descending
var compareDate = function (emp1: Emp, emp2: Emp) {
    var emp1Date = new Date(emp1.date).getTime();
    var emp2Date = new Date(emp2.date).getTime();
    return emp1Date > emp2Date ? -1 : 1;  
}
Output is
0: {id: "51", name: "Abc", date: "2018-10-05"}
1: {id: "5", name: "Kiran", date: "2018-05-05"}
2: {id: "1", name: "Frank", date: "2017-05-05"}
3: {id: "2", name: "Tom", date: "2016-05-05"}

Underscore Array Sort Example

UnderscoreJS is a javascript library which provides a lot of utility functions. It provides sortBy function which accepts an array and a function as an argument. This library can be used in javascript or typescript applications using npm package manager installation and configuring module Here is an example of array string sorting in descending
var sortedArray=_.sortBy(["four", "one", "zero"], function (value) { return value.toLowerCase(); });
console.log(sortedArray);
output is
["four","one","zero"]

Typescript - Beginner Guide to Switch case tutorial with examples

In this blog post, we are going to learn Switch case statement with examples

Switch case Introduction
Typescript Switch case tutorial

switch case is a kind of conditional expression which checks and evaluates the expression and matched case block of code executes. This is used in place of if and else conditional expressions. It will avoid multiple if and else statements to simplify the code 

Syntax

switch(conditionalexpression)
{
case value_expression:
// body statements
break;
case value_expression1:
// body statements
break;
default:
// body statements
break;
}
conditionalexpression
conditional Expression is evaluated and matching code block is finding out using case and default 
Case Block - This code is executed when Conditional Expression is matched with case block 
Default Block - This code is executed when Conditional Expression is not matched with case block Break keyword is used to break or exit from current case block and it is optional. If it is not used, remaining cases will be executed after executing matched case statement

Example

Here Single case statement is used and the default is used if none of the cases are matched.
var value = 'a';
switch (value) {
  case 'a':
    console.log(' Letter a Checked');
    break;
  case 'b':
    console.log(' Letter b Checked');
    break;
  default:
    console.log(' default letter Checked');
}
Output is
Letter a Checked

Multiple Switch cases statement Example

Multiple cases can be placed for a single code of block. Here is an example of this
var value = 'c';
switch (value) {
    case 'a':
        console.log(' Letter a Checked');
        break;
  case 'b':
  case 'c':
  case 'd':
        console.log(' Letter b,c and d Checked');
    break;
  default:
        console.log(' default letter Checked');
    break;
}
Output is
Letter b,c and d Checked

Switch Case Enum example

In switch expression, Used Enum constants. and also provided multiple case statements with enum constants
enum Day {
  MONDAY,
  TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
  SUNDAY
}
case Day.SATURDAY:
function isWorkingDay(day: Day) { switch (day) { case Day.SUNDAY: console.log('holiday'); break; default: console.log('working day'); break; } } const tuesday = Day.TUESDAY; const sunday = Day.SUNDAY; isWorkingDay(tuesday); // working day isWorkingDay(sunday); // holiday
Output is
working day
holiday

Typescript Configuration - noFallthroughCasesInSwitch 

noFallthroughCasesInSwitch value is boolean ie true or false. 
This can be configured in tsconfig.json of typescript application.This is used to return an error for fall through switch cases Following is switch case fallthrough example where there are no break statements. if noFallthroughCasesInSwitch=true, The below case is not allowed
switch(value) {
    case 1:
        // statements
    case 2:
// statements 2
}