Friday, April 5, 2024

Angular Two-Way Data Binding With Examples

In this article you will learn how to do two-way data binding in Angular using ngModel directive.


What is two-way binding

Angular one way data binding provides unidirectional binding either:

From component (Type Script code) to template (HTML view) in the form of String interpolation, property binding.

OR

From template (HTML view) to component (Type Script code) in the form of event binding.

In Angular two-way binding both of these one way bindings are combined to create a two-way flow of data between a component class and its template. So, two-way binding does both of these-

  1. If a property in the component is changed that change flows to the view.
  2. Same way change in view is reflected in the bound property in the component.

You can see that the former is property binding where as the latter is event binding and the combination of both results in two-way binding in Angular.

Angular Two-Way Data Binding

Syntax of Angular two-way binding

Syntax for two-way data binding in Angular is [()]. The [()] syntax combines the brackets of property binding, [], with the parentheses of event binding, ().

This syntax for two-way binding is also known as banana in a box.

[( )] = BANANA IN A BOX

It is just a visual way to remember that the parentheses go inside the brackets.

How to use two-way binding in Angular

In Angular ngModel directive is used for two-way bindings. It simplifies creating two-way data bindings on form elements like input element.

[(ngModel)] = "[PROPERTY_IN_COMPONENT]"  

For example: <input type="text" [(ngModel)]="userName" />

If userName property in the component has an initial value that is shown as the value of the input. Also any change in the value done by the user in the view changes the bound property value in the component too.

For using the ngModel directive in a two-way data binding, you must do these two things-

  • Import the FormsModule
  • Add it to the NgModule's imports list
import { FormsModule } from '@angular/forms';
..
..
@NgModule({
  ..
  ..

  imports: [
    BrowserModule,
    FormsModule
  ],
  ..
  ..
})
export class AppModule { }

You could achieve the same result with separate bindings to the <input> element's value property and input event:

<input [value]="userName" (input)="userName=$event.target.value">

or like this-

<input [ngModel]="userName" (ngModelChange)="userName=$event">

Using [(ngModel)] simplifies the two-way data binding with a shorter syntax. Note that, this [(ngModel)] syntax can only set a data-bound property. If you need to do something more, you can write the expanded form as shown above. For example, the following changes the <input> value to uppercase:

<input [ngModel]="userName" (ngModelChange)="setUppercaseName($event)">

Angular two-way binding example

1. Here is an example with a single property userName in the component.

import { 
  Component
 } from '@angular/core';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  userName = "Rita";
  constructor(){}  
}

Template

<div>
  <label for="username">User Name:</label>
  <input [(ngModel)]="userName" id="username">
  <p>{{ userName }}</p>
</div>

In the template as you can see target of two-way binding is ngModel directive and the expression is the property "userName" property of the component.

On running the example you get the output as-

angular twoway data binding example

Since property “userName” has an initial value so that value is displayed in the template.

Now if you change that value in the input element, that changed value would be reflected in the component too. Using String interpolation that value is fetched from the component and shown below the input element.

2. Two-way binding with fields of a model can be done in a similar way. Let’s say there is a Model class User with 2 fields name and age.

user.model.ts

export class User {
  name: string;
  age: number;
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

user.component.ts

In the component, instance of the Model class User is created and initialized with values.

import { Component } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  user: User;
  constructor(){
    // Initializing User instance
    this.user = new User('Jack Ryan', 56);
  }
}

user.component.html

<div class="container">
  <div class="mb-3">
    <label for="username" class="form-label">User Name</label>
    <input class="form-control" [(ngModel)]="user.name" id="username">
    <p>{{ user.name }}</p>
  </div>
  <div class="mb-3">
    <label for="age" class="form-label">Age</label>
    <input class="form-control" id="age" [(ngModel)]="user.age">
    <p>{{ user.age }}</p>
  </div>
</div>

That's all for this topic Angular Two-Way Data Binding With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Custom Two-Way Data Binding
  2. Angular Attribute Binding With Examples
  3. Angular @Input and @Output Example
  4. Angular ngIf Directive With Examples
  5. Angular ngClass Directive With Examples

You may also like-

  1. Injector Hierarchy and Service Instances in Angular
  2. What is Client Side Routing in Angular
  3. Checkbox in Angular Form Example
  4. How to Setup Angular
  5. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  6. Serialization and Deserialization in Java
  7. Reading Delimited File in Java Using Scanner
  8. Bubble Sort Program in Python

Introduction to Node.js

This tutorial gives an introduction to Node.js, advantages of using Node.js and some features of Node.js.

Node.js is an open-source and cross-platform JavaScript runtime environment which gives you the capability to run JavaScript code on the server side.

JavaScript from browser to server

JavaScript is typically used in the browser to manipulate the DOM, which helps in making your web page dynamic.

Browsers have a JavaScript engine that parses and executes JavaScript code. For example, Firefox browser uses SpiderMonkey, Safari uses JavaScriptCore, Chrome browser uses V8 JavaScript engine to execute JavaScript in the browser.

Node.js, using the same V8 engine capabilities, allows you to run JavaScript code on the server-side. That makes Node.js one of the popular choices for developing web applications, RESTful APIs and microservices.

Node.js brings features to the JavaScript like working with the local file system, connecting to the DB which are not possible in the traditional JavaScript code running on the browser.

You can also create utility scripts using NodeJS, where you can create a JavaScript file and run that file with in the NodeJS runtime environment. Here is a simple example which uses 'fs' module to write content to the file using JavaScript.

helloworld.js

const fs = require('fs');
console.log('Hello from nodeJS');
fs.writeFileSync('Hello.txt', 'Hello from nodeJS');

You can go to the location where you have saved this file and run node helloworld.js to execute it. Successful execution should create a file Hello.txt at the same location where the code file resides with the given content.

Using JavaScript to develop server-side applications is a huge plus point in the favour of Node.js as the same frontend developers that write JavaScript for the browser can now write the server-side code without a steep learning curve of learning a completely different language.

Features of Node.js

Here are some of the features of Node.js.

1. Node.js is single-threaded

Node.js is single-threaded which means it serves requests without creating a new thread for each request. You may think that being single-threaded should make Node.js quite slow as no new threads are spawned to work concurrently. That is not true, by using a combination of non-blocking code, event loop and callbacks Node.js is capable of handling thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency.

2. Node.js uses non-blocking paradigm

As per Node.js documentation "libraries in Node.js are written using non-blocking paradigms, making blocking behaviour the exception rather than the norm."

When Node.js performs an I/O operation, like reading from the network, accessing a database or the filesystem it doesn't block the thread until the operation is finished wasting CPU cycles waiting. Node.js will resume the operations when the operation is finished.

Suppose you are doing a I/O operation like reading a file in a framework that uses blocking I/O in that case events may be as given below-

  1. Send the I/O request to the filesystem.
  2. Wait until the operation is finished.
  3. Once the operation is finished return the content of the file.
  4. Continue with the next request

Same I/O operation with Node.js which uses non-blocking I/O.

  • Send the I/O request to the filesystem.
  • Continue with the next request
  • When the operation is finished, a callback is executed to handle the result.

That's all for this topic Introduction to Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Install Node.js and NPM in Windows
  2. JavaScript Arrow Function With Examples

You may also like-

  1. Bounded Type Parameter in Java Generics
  2. Nested Route (Child Route) in Angular
  3. React Declarative Approach
  4. Constructor chaining in Java
  5. Lambda Expression Examples in Java
  6. Java ThreadLocal Class With Examples
  7. Reading File in Java Using BufferedReader
  8. Bubble Sort Program in Python

Thursday, April 4, 2024

Method Overriding in Java

In a parent-child relation between classes, if a method in subclass has the same signature as the parent class method then the method is said to be overridden by the subclass and this process is called method overriding in Java.

Rules for method overriding in Java

  1. Overridden method must have the same name and same number and type of parameters in both parent and child classes.
  2. In the case of parent-child relationship if two classes have the method with same name and signature then only it is considered as method overriding, otherwise it is method overloading.
  3. The visibility of access modifier can't be reduced in the child class method. For example if the method is protected in the parent class then the overridden child class method can have the modifier as public (visibility can be increased) but not as private (reduced visibility).
  4. In case of method overriding, return type of the child class method should be of the same type or the sub type of the parent class' method return type. Read more about it in this post- Covariant Return Type in Java
  5. Java exception handling has certain rules in place for method overriding.
    If parent class method doesn't throw any exception then the child class method can throw only unchecked (runtime) exceptions not checked exceptions.
    If parent class method throws an exception then the child class method can throw the same exception, subtype exception of the exception declared in the superclass method or no exception at all.
    Read more about rules regarding method overriding with respect to exception handling in this post- Java Exception Handling And Method Overriding

Method overriding in Java Example

In the example there is a super class Parent and a sub-class Child. In the super class there is a method dispayData() which is overridden in the sub-class to provide sub-class specific implementation.

class Parent {
 private int i;
 // Constructor
 Parent(int i){
  this.i = i;
 }
 // Method with no param
 public void dispayData(){
  System.out.println("Value of i " + i);
 } 
}

class Child extends Parent{
 private int j;
 // Constructor
 Child(int i, int j){
  // Calling parent class constructor
  super(i);
  this.j = j;
 }
 // Overridden Method
 public void dispayData(){
  System.out.println("Value of j " + j);
 } 
}

public class OverrideDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Child child = new Child(5, 7);
  child.dispayData();  
 }
}

Output

Value of j 7

It can be noticed here that when displayData() is invoked on an object of class Child, the overridden displayData() method of the child class is called.

Benefits of method overriding in Java

Method overriding allows java to support run-time polymorphism which in turn helps in writing more robust code and code reuse.

Method overriding also helps in hierarchical ordering where we can move from general to specific.

If we use the same example to demonstrate run time polymorphism here.
class Parent {
 private int i;
 // Constructor
 Parent(int i){
  this.i = i;
 }
 // Method with no param
 public void dispayData(){
  System.out.println("Value of i " + i);
 } 
}

class Child extends Parent{
 private int j;
 // Constructor
 Child(int i, int j){
  // Calling parent class constructor
  super(i);
  this.j = j;
 }
 // Overridden Method
 public void dispayData(){
  System.out.println("Value of j " + j);
 } 
}

public class OverrideDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Child child = new Child(5, 7);
  Parent parent = new Parent(8);
  // calling parent displayData method
  parent.dispayData();
  // parent holding the reference of child
  parent = child;
  // child class displayData method will be called
  parent.dispayData();  
 }

}

Output

Value of i 8
Value of j 7

It can be noticed here that initially parent object calls displayData() method of parent class, later at run time the reference is changed and the parent is assigned the reference of child class. Now, when the displayData() method is called on the parent object, it calls the overridden method of the class Child.

Points to note-

  • If method in the sub-class has the same name and signature as the parent class method then only it is called method overriding otherwise it is method overloading.
  • Method overriding allows java to support run-time polymorphism.
  • Method overriding helps in hierarchical ordering where we can move from general to specific. In super class a method can have a general implementation where as the sub classes provide the more specific implementation by overriding the parent class method.
  • If a method is declared as final in parent class then it can not be overridden by sub classes.
  • If a method is declared as abstract in the parent class then the sub class has to provide implementation for those inherited abstract methods

That's all for this topic Method Overriding in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Method Overloading in Java
  2. Inheritance in Java
  3. Abstraction in Java
  4. Java Exception Handling And Method Overriding
  5. Java OOP Interview Questions And Answers

You may also like-

  1. finalize method in Java
  2. Association, Aggregation and Composition in Java
  3. Why main Method static in Java
  4. Varargs (Variable-length Arguments) in Java
  5. How to read input from console in Java?
  6. Difference Between sleep And wait in Java Multi-Threading
  7. Race condition in Java multi-threading
  8. How to Loop or Iterate an Arraylist in Java

Wednesday, April 3, 2024

Java Stream API Tutorial

If we have to point out the most important inclusion in Java 8 apart from lambda expressions then that has to be Stream API in Java. Stream API usually works in conjunction with lambda expression and provide an easy yet efficient way to perform data manipulation operations like sort, filter, map, reduce etc.

This Javs Stream API tutorial gives an overview of what exactly is a stream in Stream API and what all types of Stream operations are there.


What is Stream in Java Stream API

A stream can be visualized as a pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)).

Stream API in Java
Stream data flow

Tuesday, April 2, 2024

Reflection in Java - Getting Method Information

Reflection in Java class gives a good idea about how class is an entry point to all the Reflection APIs. Once you have Class object you can get information about members of the class like fields, constructors, methods. In this post we'll see how you can get method information using Java Reflection API.


Member Interface in Java Reflection API

With in the Reflection hierarchy an interface java.lang.reflect.Member is defined which is implemented by java.lang.reflect.Field, java.lang.reflect.Method, and java.lang.reflect.Constructor classes. Thus Member is an interface that provides identifying information about a single member (a field or a method) or a constructor.

This post talks about Method class and how it can be used to get information about methods using reflection. Class methods have return values, parameters, and may throw exceptions. The java.lang.reflect.Method class provides methods for obtaining the type information for the parameters and return value. It may also be used to invoke methods on a given object.

How to get Method object

Once you have instance of the Class you can use any of the following 4 methods for getting information about methods of the class.

  • getMethod(String name, Class<?>... parameterTypes)- Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.
  • getMethods()- Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
  • getDeclaredMethod(String name, Class<?>... parameterTypes)- Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
  • getDeclaredMethods()- Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Getting method information using Java reflection example

As a preparation for the example code let’s have a class called Parent.java which will be extended by the class ChildClass.java which is the class we are going to examine. There is also an interface IntTest.java which is implemented by ChildClass.java.

Parent class

public class Parent {
  String name;
  Parent(String name){
    this.name = name;
  }
  public void displayName(String name){
    System.out.println("Hello - " + name);
  }  
  public String getName(){
    return name;
  }
}

IntTest interface

public interface IntTest {
 public void showValue();
}

ChildClass.java

public class ChildClass extends Parent implements IntTest{
 private int value;
 //Constructor
 public ChildClass(String name, int value) {
  super(name);
  this.value = value;
 }

 @Override
 public void showValue() {
  System.out.println("Value - " + value);  
 }
}

Now let’s see how you can get method information using all the four methods mentioned above.

import java.lang.reflect.Method;
import java.util.Arrays;

public class ReflectMethod {
  public static void main(String[] args) {
    try {
      // Getting Class instance
      Class<?> c = Class.forName("org.netjs.prog.ChildClass");
            
      // Using getMethod(methodName, parameters)
      Method method = c.getMethod("displayName", String.class);
      System.out.println("Method params " + Arrays.toString(method.getParameters()));
            
      // Will throw exception
      /*method = c.getDeclaredMethod("displayName", String.class);
      System.out.println("Method params " + Arrays.toString(method.getParameters()));*/
            
      Method[] methodArr = c.getMethods();
      System.out.println("All methods " + Arrays.toString(methodArr));
            
      methodArr = c.getDeclaredMethods();
      System.out.println("Class methods " + Arrays.toString(methodArr));
            
    } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Output

Method params [java.lang.String arg0]

All methods [public void org.netjs.prog.ChildClass.showValue(), public java.lang.String org.netjs.prog.Parent.getName(), 
public void org.netjs.prog.Parent.displayName(java.lang.String), 
public final void java.lang.Object.wait() throws java.lang.InterruptedException, 
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException, 
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, 
public boolean java.lang.Object.equals(java.lang.Object), public java.lang.String java.lang.Object.toString(), 
public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), 
public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll()]

Class methods [public void org.netjs.prog.ChildClass.showValue()]

First call to the getMethod with parameters method name and parameter types returns the matching method. Then parameters of the method are printed using the getParameters() method of the Method class.

Second call (Which is commented) will throw NoSuchMethodException as the method displayName is inherited from the parent class and getDeclaredMethod() will work for the methods with in the class.

getMethods() will return all the methods of the class and also the inherited methods.

GetDeclaredMethods() will return all the methods of the class but not the inherited one.

Getting method parameter types and return type using reflection

If we have a class called ChildClass as follows then we can get its method parameter types and return type using reflection.

ChildClass.java

public class ChildClass extends Parent implements IntTest{
 private int value;
 //Constructor
 public ChildClass(String name, int value) {
  super(name);
  this.value = value;
 }

 @Override
 public void showValue() {
  System.out.println("Value - " + value);  
 }
 
 public String getValue(String name) throws Exception{
  return "Hello" + name;
 }
}
// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
methodArr = c.getDeclaredMethods();
for(Method m: methodArr){
  System.out.println("For Method - " + m.getName() + " Parameter types are - " + Arrays.toString(m.getParameterTypes()));
  System.out.println("For Method - " + m.getName() + " Return type " + m.getReturnType());
}

Output

For Method - getValue Parameter types are - [class java.lang.String]
For Method - getValue Return type class java.lang.String
For Method - showValue Parameter types are - []
For Method - showValue Return type void

Getting method modifiers using reflection

If you want to get information about the modifiers of the methods of the class you can use getModifiers() method whose return type is int.

// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
methodArr = c.getDeclaredMethods();
for(Method m: methodArr){
  System.out.println("For Method - " + m.getName() + 
    " modifier is - " + Modifier.toString(m.getModifiers()));
}

Output

For Method - getValue modifier is – public
For Method - showValue modifier is – public

Getting thrown exceptions using reflection

If you want to get information about types of exceptions declared to be thrown by the methods of the class you can use getExceptionTypes() method.

// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
methodArr = c.getDeclaredMethods();
for(Method m: methodArr){
  System.out.println("For Method - " + m.getName() + " Thrown Exceptions  - " 
    + Arrays.toString(m.getExceptionTypes()));
}

Output

For Method - getValue Thrown Exceptions  - [class java.lang.Exception]
For Method - showValue Thrown Exceptions  - []

Invoking method using reflection

Using Java reflection API you can also invoke methods on a class at runtime. Methods are invoked using java.lang.reflect.Method.invoke() method. The first argument is the object instance on which this particular method is to be invoked. (If the method is static, the first argument should be null.) Subsequent arguments are the method's parameters.

// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
// Getting class object
ChildClass ch = new ChildClass("Test", 10);
Method method = c.getDeclaredMethod("getValue", String.class);
try {
  String result = (String)method.invoke(ch, "Reflection");
  System.out.println("Method invocation returned - " + result);
} catch (IllegalAccessException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
} catch (IllegalArgumentException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
} catch (InvocationTargetException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

Output

Method invocation returned – HelloReflection

Invoking private method of the class using reflection

You can even invoke the private methods of the class using Reflection in Java. Using getDeclaredMethod() you can get the private methods of the class.

Once you have the method object you can use the setAccessible() method which is inherited from class java.lang.reflect.AccessibleObject to set the access for the private method as true at run time and then invoke it from another class.

Let’s say we have a ChildClass as follows with a private method getValue().

public class ChildClass extends Parent implements IntTest{
  private int value;
  //Constructor
  public ChildClass(String name, int value) {
    super(name);
    this.value = value;
  }

  @Override
  public void showValue() {
    System.out.println("Value - " + value);  
  }
 
  private String getValue(String name) throws Exception{
    return "Hello" + name;
  }
}

Now you want to invoke this private method.

// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
// Getting class object
ChildClass ch = new ChildClass("Test", 10);
Method method = c.getDeclaredMethod("getValue", String.class);
method.setAccessible(true);
try {
    String result = (String)method.invoke(ch, "Reflection");
    System.out.println("Method invocation returned - " + result);
} catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (InvocationTargetException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Output

Method invocation returned – HelloReflection

You can comment the line where access to the method is set as true.

//method.setAccessible(true);

Then if you execute it you will get the exception as follows -

java.lang.IllegalAccessException: Class org.netjs.prog.ReflectMethod can not access a member of class 
org.netjs.prog.ChildClass with modifiers "private"
 at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
 at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
 at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
 at java.lang.reflect.Method.invoke(Unknown Source)
 at org.netjs.prog.ReflectMethod.main(ReflectMethod.java:32)

That's all for this topic Reflection in Java - Getting Method Information. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Reflection in Java - Getting Field Information
  2. Reflection in Java - Getting Constructor Information
  3. Reflection in Java - Array
  4. Generating Getters And Setters Using Reflection in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Externalizable Interface in Java
  2. Java Concurrency Interview Questions And Answers
  3. FlatMap in Java
  4. Method Reference in Java
  5. Wildcard in Java Generics
  6. Race Condition in Java Multi-Threading
  7. Switch Case Statement in Java With Examples
  8. static Block in Java

Monday, April 1, 2024

Angular Reactive Form Validation Example

In the post Angular Reactive Form Example we saw an example of creating a simple Reactive form in Angular in this post we’ll add to that example to create an Angular reactive form with validation.

Tracking control states

NgModel directive used with the form controls tracks the state of that control. Three things you'll look for while validating form fields are-

  1. Whether user touched the control or not,
  2. If the value of the form control is changed
  3. If the entered value is valid or invalid.

Saturday, March 30, 2024

Angular Class Binding With Examples

In this post we’ll discuss another one-way binding known as Angular class binding. Using class binding you can add and remove CSS classes dynamically from an element's class attribute.

Angular class binding syntax

Syntax of class binding is similar to property binding, square brackets are used for class binding too. To create a class binding, start with the prefix class followed by a dot (.) and the name of the CSS class.

[class.CSS_CLASS]="isRequired"

Here CSS class CSS_CLASS is added when the bound expression is truthy (i.e. isRequired is true), and it removes the class when the expression is falsy (i.e. isRequired is false).

Adding multiple CSS classes

Angular class binding can also be done to multiple classes by using a generic [class] binding without the dot (for example, [class]="classExpr").

The expression can be a space-delimited string of class names. For example

[class]="my-class-1 my-class-2 my-class-3"

You can format it as an object (object, Array, Map, Set, etc) with class names as the keys and truthy/falsy expressions as the values.

As key/value pair- [class]="{my-class-1: true, my-class-2: false}”

As an array - [class]=['my-class-1', 'my-class-2']

Angular class binding examples

1. In the example we display region wise sales figures and want to highlight the sales figures which are good in different color and the sales figures which are not satisfactory in different color. For that styling class binding is used with the condition on the sales figures.

region.model.ts

Model class with fields.

export class Region {
  region: string;
  regionalManager: string;
  sales: number;
  constructor(region: string, regionalManager: string, sales: number) {
    this.region = region;
    this.regionalManager = regionalManager;
    this.sales  = sales;
  }
}

Component class

Component used Region model so that class is imported. There is an array of type Region in which instances of Region are stored.

import { 
    Component
 } from '@angular/core';
import { Region } from './region.model';
@Component({
  selector: 'app-region',
  templateUrl: './region.component.html',
  styleUrls: ['./region.component.css']
})
export class RegionComponent{
  regions: Region[];
  constructor(){
    //Adding Region instances to regions array
    this.regions = [new Region('East', 'Jack', 145),
                   new Region('West', 'Jerry', 225),
                   new Region('North', 'Lisa', 300),
                   new Region('South', 'Randy', 175)] ;
  }
}

CSS Class

.domore {
  background-color: #d41e2e;
  color: #ffffff;
}
.satisfactory {
  background-color:green;
  color: #ffffff;
}

Template

<div class="container">
  <table class="table table-sm table-bordered mt-4">
    <tr>
      <th>Region</th>
      <th>Manager</th>
      <th>Sales (in millions)</th>
    </tr>
    <tr *ngFor="let region of regions" [class.domore] = "region.sales < 150"
      [class.satisfactory] = "region.sales > 250">
      <td>{{region.region}}</td>
      <td>{{region.regionalManager}}</td>
      <td>{{region.sales}}</td>
    </tr>
  </table>
</div>

With the <tr> element there are two class bindings

 [class.domore] = "region.sales < 150"
 [class.satisfactory] = "region.sales > 250"

When sales is less than 150 domore CSS class is added, when sales is greater than 250 then satisfactory CSS class is added.

class binding example

2. In this example we’ll see how to do class binding for multiple CSS classes. To demonstrate that one more CSS class is added.

CSS

.domore {
  background-color: #d41e2e;
  color: #ffffff;
}
.satisfactory {
  background-color:green;
  color: #ffffff;
}
.brd {
  border: 2px solid black;
}

Component

import { 
  Component
} from '@angular/core';
import { Region } from './region.model';
@Component({
  selector: 'app-region',
  templateUrl: './region.component.html',
  styleUrls: ['./region.component.css']
})
export class RegionComponent{
  regions: Region[];
  constructor(){
  //Adding Region instances to regions array
  this.regions = [new Region('East', 'Jack', 145),
                  new Region('West', 'Jerry', 225),
                  new Region('North', 'Lisa', 300),
                  new Region('South', 'Randy', 175)];
  }

  getCssClasses(sales : Number){
    if(sales < 150){
      return "domore brd";
    }else if(sales > 250){
      return "satisfactory brd";
    }
  }
}

In the component a method getCssClasses() is added in which sales figures are passed as argument. Based on the condition two CSS classes are passed.

Template

<div class="container">
  <table class="table table-sm table-bordered mt-4">
    <tr>
      <th>Region</th>
      <th>Manager</th>
      <th>Sales (in millions)</th>
    </tr>
    <tr *ngFor="let region of regions" [class] = "getCssClasses(region.sales)">
      <td>{{region.region}}</td>
      <td>{{region.regionalManager}}</td>
      <td>{{region.sales}}</td>
    </tr>
  </table>
</div>

In the <tr> element generic class binding is used with a bound method. From the method, space delimited string of CSS class names is returned.

Angular Class Binding

That's all for this topic Angular Class Binding With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Style Binding With Examples
  2. Angular Attribute Binding With Examples
  3. Angular Custom Event Binding Using @Output Decorator
  4. Angular Custom Two-Way Data Binding
  5. Angular ngClass Directive With Examples

You may also like-

  1. Angular Disable Button Example
  2. Angular @Component Decorator
  3. Angular - Call One Service From Another
  4. How to Add Bootstrap to Angular Application
  5. JVM Run-Time Data Areas - Java Memory Allocation
  6. Adding Tomcat Server to Eclipse
  7. Java Reflection API Tutorial
  8. static Reference to The Non-static Method or Field Error

Friday, March 29, 2024

Interface Static Methods in Java

Java 8 has added support for interface default methods as well as interface static methods which is one of the important change in Java 8 along with the addition of lambda expressions and stream API. In this post we'll see how to use interface static methods in Java and what are the rules for using them


Static method in Java interface

Like static methods in a class, now we can write static method in interfaces too. Static methods in an interface can be called independently of any object just like how static methods are called in a class.

General form of calling the interface static method

Static methods in an interface are called by using the interface name preceding the method name.

InterfaceName.staticMethodName;

Java interface static method example

public interface MyInterface {
 int method1();
 // default method, providing default implementation
 default String displayGreeting(){
    return "Hello from MyInterface";
 }
 //static method
 static int getDefaultAmount(){
    return 0;
 }
}
public class MyClass{ 
  public static void main(String[] args) { 
    int num = MyInterface.getDefaultAmount();
    System.out.println("num " + num);
  } 
}

Output

num 0

In the example code interface MyInterface has one static method getDefaultAmount(). Note that MyClass is not even implementing the interface MyInterface still static method of the MyInterface can be called from MyClass using the call MyInterface.getDefaultAmount();. This is because, no implementation or reference of the interface is required to call the static method.

Interface static methods are not inherited

Static interface methods are not inherited by-

  • Implementing classes
  • Extending interfaces

Here interface B is extending mentioned interface MyInterface, but it can not access the static method of interface MyInterface.

interface B extends MyInterface{ 
  default String displayGreeting(){
    B.getDefaultAmount(); // Compiler Error 
    return "Hello from MyInterface";
  }
}

Same way even if MyClass implements MyInterface still it can not access static method of MyInterface, either by using the class name or by using the object reference.

public class MyClass implements MyInterface{
  // provides implementation for the non-default method
  // of the interface
  @Override
  public int method1() {
    return 10;
  }
  //Overriding the default method of MyInterface
  public String displayGreeting(){
    return MyInterface.super.displayGreeting();
  }
 
  public static void main(String[] args) {
    MyInterface myInt = new MyClass();

    int num = MyInterface.getDefaultAmount();
    System.out.println("num " + num);
    MyClass.getDefaultAmount(); // Compiler error
    myInt.getDefaultAmount();// Compiler error
  } 
}

Hiding interface static method

Though implementing class can't provide implementation for the static methods of an interface but the implementing class can hide the interface static method in Java by providing a method with the same signature in the implementing class.

public interface MyInterface {
  int method1();
  // default method, providing default implementation
  default String displayGreeting(){
     return "Hello from MyInterface";
  }
  static int getDefaultAmount(){
     return 0;
  }
}
Implementing class
public class MyClass implements MyInterface{
  // provides implementation for the non-default method
  // of the interface
  @Override
  public int method1() {
    return 10;
  }
  //Overriding the default method of MyInterface
  public String displayGreeting(){
    return MyInterface.super.displayGreeting();
  }
  // static method
  public static int getDefaultAmount(){
    return 5;
  }
 
  public static void main(String[] args) {
    MyInterface myInt = new MyClass();

    int num = MyInterface.getDefaultAmount();
    System.out.println("num - Interface " + num);
    System.out.println("num - Class " + MyClass.getDefaultAmount());  
  } 
}

Output

num - Interface 0
num - Class 5

Here getDefaultAmount() method is provided in the MyClass class also which hides the interface static method.

Advantages of Java interface static methods

  • Interface static methods can be used for providing utility methods.
  • With Interface static methods we can secure an implementation by having it in static method as implementing classes can't override them. Though we can have a method with same signature in implementing class but that will hide the method won't override it.

That's all for this topic Interface Static Methods in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Marker Interface in Java
  2. Difference Between Abstract Class And Interface in Java
  3. PermGen Space Removal in Java 8
  4. Lambda Expressions in Java 8
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Functional Interface Annotation in Java
  2. Java Stream API Examples
  3. New Date And Time API in Java 8
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. How HashMap Works Internally in Java
  6. Java Abstract Class and Abstract Method
  7. Difference Between throw And throws in Java
  8. final Vs finally Vs finalize in Java

Thursday, March 28, 2024

Interface Default Methods in Java

Java 8 has added support for default methods as well as static methods to interfaces. In this post we'll talk about interface default methods in Java.


Need for interface default methods in Java

There was a problem with interfaces in Java that they were not open to extension, which means if there was a need to add new method to an interface it would have broken the existing implementations of that interface. Thus it was imperative that all the classes implementing that interface had to provide implementation for the newly added method, even if the method was not needed. Thus Java interfaces were not easy to evolve.

One example that comes to mind is Java MapReduce API for Hadoop, which was changed in 0.20.0 release to favour abstract classes over interfaces, since they are easier to evolve. Which means, a new method can be added to abstract class (with default implementation), without breaking old implementations of the class.

Default method in Java interface

Java 8 onward it is possible to add default methods (having default implementation) in Java interfaces, thus making them easier to evolve. With the addition of default method to an interface, addition of new method, even to an interface will not break the pre-existing code.

Interface default method should be used for backward compatibility. Whenever there is a need to add new methods to an existing interface, default methods can be used so that existing implementing classes don't break and not forced to provide implementation for the newly added methods.

Java Interface Default Method Example

An interface default method in Java is defined the same way a method will be defined in a class. One difference is that in interface, default method is preceded by the keyword default.

public interface MyInterface {
  int method1();
  // default method, providing default implementation
  default String displayGreeting(){
    return "Hello from MyInterface";
  }
}
public class MyClass implements MyInterface{
  // provides implementation for the non-default method
  // of the interface
  @Override
  public int method1() {
    return 10;
  }
  public static void main(String[] args) {
    MyInterface myInt = new MyClass();
    System.out.println("Value " +  myInt.method1());
    // Calls the default method provided by interface itself
    System.out.println("Greeting " + myInt.displayGreeting());
  }
}

Output

Value 10
Greeting Hello from MyInterface

It can be seen that in MyInterface interface there is a default method displayGreeting() with a default implementation. Here implementing class is not overriding and providing its own implementation of the default method thus the default implementation is used.

Implementing class can provide its own implementation of a default method by overriding it. If we use the same interface and class as used above and override the displayGreeting() method to change the implementation.

public class MyClass implements MyInterface{
  // provides implementation for the non-default method
  // of the interface
  @Override
  public int method1() {
    return 10;
  }
  //Overriding the default method of MyInterface
  public String displayGreeting(){
    return "Hello from MyClass";
  }
 
  public static void main(String[] args) {
    MyInterface myInt = new MyClass();
    System.out.println("Value " +  myInt.method1());
    // Calls the default method provided by interface itself
    System.out.println("Greeting " + myInt.displayGreeting());
  }
}

Output

Value 10
Greeting Hello from MyClass

It can be seen how output has changed and now the displayGreeting() method of the implementing class is used.

Interface default methods and multiple inheritance issues

With the inclusion of default methods, interfaces may have multiple inheritance issues. Though an interface can't hold state information (interface can't have instance variables), so state information can't be inherited, but behavior in form of default method may be inherited which may cause problems. Let's see it with an example-

Let's assume there are two interfaces A and B and both have default method displayGreeting(). There is a class MyClass which implements both these interfaces A and B.

Now consider the scenarios-

  • Which implementation of default method displayGreeting() will be called when MyClass is implementing both interfaces A and B and not overriding the displayGreeting() method.
  • Which implementation of displayGreeting() will be called when MyClass is implementing both interfaces A and B and overriding the displayGreeting method and providing its own implementation.
  • If interface A is inherited by interface B, what will happen in that case?

To handle these kinds of scenarios, Java defines a set of rules for resolving default method conflicts.

  • If implementing class overrides the default method and provides its own functionality for the default method then the method of the class takes priority over the interface default methods.
    For Example, if MyClass provides its own implementation of displayGreeting(), then the overridden method will be called not the default method in interface A or B.
  • When class implements both interfaces and both have the same default method, also the class is not overriding that method then the error will be thrown.
    "Duplicate default methods named displayGreeting inherited from the interfaces"
  • In case when an interface extends another interface and both have the same default method, the inheriting interface default method will take precedence. Thus, if interface B extends interface A then the default method of interface B will take precedence.

Use of Super with interface default methods

As stated above when class implements 2 interfaces and both have the same default method then the class has to provide an implementation of its own for the default method otherwise error will be thrown. From the implementing class if you want to call the default method of interface A or interface B, then you can call the default method of the specific interface using the super keyword from the overridden default method in the class.

Syntax for calling the default method of the specific interface using super is as follows-

InterfaceName.super.methodName();

For example, if you want to call the default method of interface A.

public interface A {
  int method1();
  // default method, providing default implementation
  default String displayGreeting(){
    return "Hello from interface A";
  }
}

interface B{
  // default method, providing default implementation
  default String displayGreeting(){
    return "Hello from Interface B";
  }
}
public class MyClass implements A, B{
  // provides implementation for the non-default method
  // of the interface
  @Override
  public int method1() {
     return 10;
  }
  //Overriding the default method of MyInterface
  public String displayGreeting(){
     return A.super.displayGreeting();
  }
 
  public static void main(String[] args) {
     A myInt = new MyClass();
     System.out.println("Value " +  myInt.method1());
     // Calls the default method provided by interface itself
     System.out.println("Greeting " + myInt.displayGreeting());
  }
}

Output

Value 10
Greeting Hello from interface A

It can be seen from displayGreeting() method of the class, using super, displayGreeting() method of interface A is called here.

Difference between Interface with default method and abstract class in Java

With interfaces also providing default methods the lines between the abstract class and interface blurs a bit in Java. But there are still certain differences between them.

  • Abstract class can have constructor, instance variables but interface can't have any of them.
  • interfaces with default methods also cannot hold state information.

Points to note-

  • With Java 8 interface default methods had been added in order to make interfaces easy to evolve.
  • With interface default method, classes are free to use the default method of the interface or override them to provide specific implementation.
  • With interface default methods there may be multiple inheritance issue if same default method is provided in more than one interfaces and a class is implementing those interfaces.
  • super can be used from the implementing class to invoke the interface default method. It's general form is InterfaceName.super.methodName();
  • Interface default methods don't change the basic traits of interface, interface still can't hold state information, it is still not possible to create an instance of an interface by itself.

That's all for this topic Interface Default Methods in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Interface in Java With Examples
  2. Marker Interface in Java
  3. Difference Between Abstract Class And Interface in Java
  4. Private Methods in Java Interface
  5. Core Java Basics Interview Questions

You may also like-

  1. Lambda expressions in Java 8
  2. Try-With-Resources in Java With Examples
  3. Java Stream API Examples
  4. strictfp in Java
  5. covariant return type in Java
  6. How and why to synchronize ArrayList in Java
  7. Java ReentrantLock With Examples
  8. Bean Scopes in Spring With Examples

Wednesday, March 27, 2024

Convert double to String in Java

In the post converting String to double in Java we have already seen ways to do that conversion. This post is about doing just the reverse; convert double to string in Java.

Concatenating with an empty String

Easiest way to convert double to a string in Java is to concatenate double with an empty string. That will give you a string value, conversion is handled for you.

public class DoubleToString {
 public static void main(String[] args) {
  double num = 78.111167d;
  String str = num + "";
  System.out.println("Value " + str);
  System.out.println("Type of str " + str.getClass().getSimpleName());
 }
}

Output

Value 78.111167
Type of str String

Here note that with double value you can use d or D (f or F, for float values).

Converting double to String in Java using valueOf() method

String class has valueOf() method which is overloaded and those variants take int, float, double, long data types as parameters. Using valueOf(double d) method you can convert double to String in Java. Method returns string representation of the passed double argument.

public class DoubleToString {
 public static void main(String[] args) {
  double num = -67.16789;
  String str = String.valueOf(num);
  System.out.println("Value " + str);
 }
}

Output

Value -67.16789

Using toString() method of the wrapper class

Each of the Number subclass (Integer, Float, Double etc.) includes a class method toString(), that will convert its primitive type to a string. Thus, using Double.toString(double d) method of the wrapper class Double, you can convert double to String in Java. Method returns a String object representing the passed double value.

public class DoubleToString {
 public static void main(String[] args) {
  double num = 124686.9698694d;
  String str = Double.toString(num);
  System.out.println("Value " + str);
 }
}

Output

Value 124686.9698694

Using String.format method

  • String format(String format, Object... args)- Returns a formatted string using the specified format string and arguments.

Here as a format you can use 'f' which means floating point and the result is formatted as a decimal number.

public class DoubleToString {

 public static void main(String[] args) {
  double num = 124686.9698694d;
  String str = String.format("%.2f", num);
  System.out.println("Value " + str);
 }
}

Output

Value 124686.97

Here note that .2f is used as format so there will be 2 decimal places. In the signature of the format() method you can see that second argument is a vararg which is of type Object. Still you can pass double primitive data type because of autoboxing.

That's all for this topic Convert double to String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Convert float to String in Java
  2. Convert double to int in Java
  3. Converting String to Enum Type in Java
  4. Java Program to Convert a File to Byte Array
  5. How to Format Date in Java Using SimpleDateFormat

You may also like-

  1. How to Convert Date And Time Between Different Time-Zones in Java
  2. Creating Tar File And GZipping Multiple Files in Java
  3. Java Program to Get All The Tables in a DB Schema
  4. How to Find The Longest Palindrome in The Given String
  5. Deadlock in Java Multi-Threading
  6. Ternary Operator in Java With Examples
  7. Functional Interfaces in Java
  8. forEach statement in Java 8

Convert float to String in Java

In the post converting String to float we have already seen ways to convert String to float in Java. This post is about doing just the reverse; convert float to string in Java.

Concatenating with an empty String

Easiest way to convert float to a string in Java is to concatenate float with an empty string. That will give you a string value, conversion is handled for you.

public class FloatToString {
 public static void main(String[] args) {
  float num = 7.345f;
  String value = num + "";
  System.out.println("Value is " + value);
  System.out.println("Type of value is " + value.getClass().getSimpleName());
 }
}

Output

Value is 7.345
Type of value is String

Converting float to String in Java using valueOf() method

String class has valueOf() method which is overloaded and those variants take int, float, double, long data types as parameters. Using valueOf(float f) method you can convert float to String in Java by passing float as an argument to the method and method returns string representation of the float argument.

public class FloatToString {
  public static void main(String[] args) {
    float num = -97.345f;
    String value = String.valueOf(num);
    System.out.println("Value is " + value);
  }
}

Output

Value is -97.345

Using toString() method of the Float wrapper class

Each of the Number subclass (Integer, Float, Double etc.) includes a class method, toString(), that will convert its primitive type to a string. Thus, using Float.toString(float f) method you can convert float to String in Java, method returns a String object representing the passed float value.

public class FloatToString {
 public static void main(String[] args) {
  float num = 78.34576865959f;
  String value = Float.toString(num);
  System.out.println("Value is " + value);
 }
}

Output

Value is 78.34577

Here note that vale has been rounded off. That is one thing to be considered while converting float values that those are not precise.

That's all for this topic Convert float to String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Convert int to String in Java
  2. Convert float to int in Java
  3. Arrange Non-Negative Integers to Form Largest Number - Java Program
  4. How to Convert Date to String in Java
  5. Java String Interview Questions And Answers

You may also like-

  1. Matrix Multiplication Java Program
  2. Reading Delimited File in Java Using Scanner
  3. How to Untar a File in Java
  4. static Block in Java
  5. Is String Thread Safe in Java
  6. Try-With-Resources in Java With Examples
  7. Java ThreadLocal Class With Examples
  8. AtomicLong in Java With Examples

Tuesday, March 26, 2024

Angular Form setValue() and patchValue()

In this tutorial we’ll see how to set values for the form controls using setValue and patchValue in Angular forms. We’ll also see the difference between setValue and patchValue methods.


setValue in Angular

setValue as the name suggests is a method used to set values. You can use it to set value of a single form control instance, form group or form array.

Monday, March 25, 2024

Java Stream API Examples

In the post Java Stream API Tutorial we have already got an introduction of Stream API. A Stream can be defined as a sequence of elements supporting sequential and parallel aggregate operations. Using these aggregation operations we can create a pipeline. Some of the aggregation operations provided are collect, concat, count, distinct, filter, forEach, limit, map, max, min, reduce, sorted. In this post we’ll see some Java stream API examples using these operations and also create pipeline consisting sequence of aggregate operations.


Java Stream API count() method example

count method returns the count of elements in the given stream.

Note that this is a special case of a reduction and it is a terminal operation.

List<Integer> myList = Arrays.asList(7, 18, 10, 24, 17, 5);  
long count = myList.stream().count();
System.out.println("Total elements in the list " + count);

This code snippet will give the count of the elements in the List.

Now if you want to get the count of the elements greater than 10 you can create a pipeline where you first filter on the predicate that you want those elements of the list whose value is greater than 10 and then count those elements.

List<Integer> myList = Arrays.asList(7, 18, 10, 24, 17, 5); 
long count = myList.stream().filter(i -> i > 10).count();
System.out.println("Total elements in the list with value greater than 10 " + count);

Java Stream API concat() method example

concat() method in Java Stream creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.

List<String> myList = Arrays.asList("1", "2", "3", "4", "5");
  
String[] arr1 = { "a", "b", "c", "d" };
// concatenating two streams
Stream<String> stream = Stream.concat(myList.stream(), Arrays.stream(arr1));
stream.forEach(System.out::print);

Output

12345abcd

Here you can see the concatenated stream is returned. If you are wondering what is this System.out::print refer Method reference in Java 8. You may also want to read about forEach statement in Java 8.

Since parameters of the concat operations are streams so all the aggregation operations can be applied to them too. As example if there are two lists having name and you want a merged list with all the names that start with “A” that can be done as follows–

List<String> nameList1 = Arrays.asList("Ram", "Amit", "Ashok", "Manish", "Rajat");
  
List<String> nameList2 = Arrays.asList("Anthony", "Samir", "Akash", "Uttam");
  
String[] arr1 = { "a", "b", "c", "d" };
// concatenating two streams
Stream<String> stream = Stream.concat(nameList1.stream().filter(n -> n.startsWith("A")), nameList2.stream().filter(n -> n.startsWith("A")));

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

Java Stream API distinct() method example

Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.

Using distinct method of the Java Stream API, duplicate elements from a collection like list can be removed very easily by creating a pipeline where distinct method will return a stream having distinct elements only which can later be collected in a list using collect method.

List<Integer> myList = Arrays.asList(7, 18, 10, 7, 10, 24, 17, 5);
  
System.out.println("Original list: " + myList);
List<Integer> newList = myList.stream().distinct().collect(Collectors.toList());

System.out.println("new List : " + newList);

Java Stream API filter() method example

filter method returns a stream consisting of the elements of this stream that match the given predicate.

Here note that Predicate is a functional interface and can be implemented as a lambda expression. In the above examples we have already used filter method.

As an example let’s say we have a list of names and we want to print names which doesn’t start with “A”.

List<String> nameList = Arrays.asList("Ram", "Amit", "Ashok", "Manish", "Rajat");
  
nameList.stream().filter(n -> !n.startsWith("A")).collect(Collectors.toList()).forEach(System.out::println);

Output

Ram
Manish
Rajat

Java Stream API limit() method example

Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.

If you want 10 random numbers, then you can use limit method with the int stream.

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

Java Stream API map() method example

Returns a stream consisting of the results of applying the given function to the elements of this stream. So, whatever function is provided is applied on all the elements of the stream. Note that this is an intermediate operation.

As Example– If you have a list of salaries and you want to increase it by 10%.

List<Integer> myList = Arrays.asList(7000, 5000, 4000, 24000, 17000, 6000);
  
myList.stream().map(i -> (i+ i * 10/100)).forEach(System.out::println);

findFirst() and findAny() methods in Java Stream API

  • findFirst()- Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order (List or Array wil be ordered, where as set or map won’t), then any element may be returned.
  • findAny()- Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)
List<String> nameList = Stream.of("amy", "nick", "margo", "desi");
Optional<String> name = nameList.stream().findFirst();
System.out.println("First Name " + name);

name = nameList.parallelStream().findAny();
System.out.println("First Name " + name);

Output

First Name Optional[amy]
First Name Optional[margo]

You can see in case of findFirst() method, first element of the list is displayed. Even with parallelStream, findFirst() will give the first element.

Whereas in case of findAny() method any random element is picked. You can see that findAny() method is used with parallelStream here.

max and min methods in Java Stream API

  • max- Returns the maximum element of this stream according to the provided Comparator.
  • min- Returns the minimum element of this stream according to the provided Comparator.

max and min are also reduction operations. Both of them are terminal operations.

List<Integer> myList = Arrays.asList(7000, 5000, 4000, 24000, 17000, 6000);
// Obtain a Stream to the array list.
Stream<Integer> myStream = myList.stream();
Optional<Integer> val = myStream.min(Integer::compare);
if(val.isPresent()){
 System.out.println("minimum value in the list " + val.get());
}  
Optional<Integer> val1 = myList.stream().max(Integer::compare);
if(val1.isPresent()){
 System.out.println("maximum value in the list " + val1.get());
}

Note that here Optional class is used. To know more about Optional class refer Optional class in Java 8.

Java Stream API sorted() method example

sorted method returns a stream consisting of the elements of this stream, sorted according to natural order or there is another variant where custom comparator can be provided.

List<Integer> myList = Arrays.asList(7000, 5000, 4000, 24000, 17000, 6000);
myList.stream().sorted().forEach(System.out::println);

Summary Statistics classes

A state object for collecting statistics such as count, min, max, sum, and average. There are different SummaryStatistics classes in Java Stream API like IntSummaryStatistics, DoubleSummaryStatistics, LongSummaryStatistics.

As example–

 
List<Integer> myList = Arrays.asList(7, 5, 4, 24, 17, 6);
IntSummaryStatistics stats = myList.stream().collect(Collectors.summarizingInt(i-> i));

System.out.println("Sum - " + stats.getSum());
System.out.println("Count " + stats.getCount());
System.out.println("Average " + stats.getAverage());
System.out.println("Max " + stats.getMax());
System.out.println("Min " + stats.getMin());

Here Collectors.summarizingInt method is used which applies an int-producing mapping function to each input element, and returns summary statistics for the resulting values.

In place of

IntSummaryStatistics stats = myList.stream().collect(Collectors.summarizingInt(i-> i));

Using mapToInt method it can also be written as -

IntSummaryStatistics stats = myList.stream().mapToInt(i -> i).summaryStatistics();

That's all for this topic Java Stream API Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Parallel Stream in Java Stream API
  2. Primitive Type Streams in Java Stream API
  3. Reduction Operations in Java Stream API
  4. Lambda Expressions in Java 8
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. How HashMap Works Internally in Java
  2. How ArrayList Works Internally in Java
  3. Java ReentrantLock With Examples
  4. Difference Between ArrayList And CopyOnWriteArrayList in Java
  5. Lock Striping in Java Concurrency
  6. Java ThreadLocal Class With Examples
  7. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  8. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring