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

Sunday, March 24, 2024

ConcurrentSkipListMap in Java With Examples

ConcurrentSkipListMap in Java is a scalable concurrent map which implements ConcurrentNavigableMap interface. Though concurrent collections like ConcurrentHashMap and CopyOnWriteArrayList were added in Java 1.5, ConcurrentSkipListMap and the similar set implementation ConcurrentSkipListSet were added in Java 1.6.


ConcurrentNavigableMap interface

ConcurrentNavigableMap interface in Java is a ConcurrentMap supporting NavigableMap operations, and recursively so for its navigable sub-maps. It was added in Java 1.6.

ConcurrentNavigableMap interface in turn extends NavigableMap interface. Where NavigableMap is a SortedMap extended with navigation methods returning the closest matches for given search targets. Methods lowerEntry, floorEntry, ceilingEntry, and higherEntry return Map.Entry objects associated with keys respectively less than, less than or equal, greater than or equal, and greater than a given key, returning null if there is no such key. Similarly, methods lowerKey, floorKey, ceilingKey, and higherKey return only the associated keys. All of these methods are designed for locating, not traversing entries.

ConcurrentSkipListMap in Java

Since ConcurrentSkipListMap implements ConcurrentNavigableMap, it is a sorted map just like TreeMap in Java (Which also implements NavigableMap interface), with added functionality of being concurrent.

ConcurrentSkipListMap is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

Java ConcurrentSkipListMap constructors

ConcurrentSkipListMap class provides four constructors, which are as follows-

  • ConcurrentSkipListMap()- Constructs a new, empty map, sorted according to the natural ordering of the keys.
  • ConcurrentSkipListMap(Comparator<? super K> comparator)- Constructs a new, empty map, sorted according to the specified comparator.
  • ConcurrentSkipListMap​(Map<? extends K,? extends V> m)- Constructs a new map containing the same mappings as the given map, sorted according to the natural ordering of the keys.
  • ConcurrentSkipListMap​(SortedMap<K,? extends V> m)- Constructs a new map containing the same mappings and using the same ordering as the specified sorted map.

ConcurrentSkipListMap class in Java implements a concurrent variant of SkipLists data structure providing expected average log(n) time cost for the containsKey, get, put and remove operations and their variants. Insertion, removal, update, and access operations safely execute concurrently by multiple threads.

All Map.Entry pairs returned by methods in ConcurrentSkipListMap class and its views represent snapshots of mappings at the time they were produced.

No nulls in ConcurrentSkipListMap

Note that ConcurrentSkipListMap class in Java does not permit the use of null keys or values because some null return values cannot be reliably distinguished from the absence of elements.

Java example creating ConcurrentSkipListMap

Let's see an example where we add some values in a ConcurrentSkipListMap and in the output it can be seen that it is sorted based on the natural ordering of its keys. In this example keys are Strings and for String natural ordering is ascending alphabetical order. So when you loop the map you'll see it is sorted based on the keys.

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

public class CSMDemo {
  public static void main(String[] args) {
    ConcurrentNavigableMap<String, String> cityMap = new ConcurrentSkipListMap<String, String>();
    cityMap.put("ND", "New Delhi");
    cityMap.put("MU", "Mumbai");
    cityMap.put("CH", "Chennai");
    cityMap.put("HD", "Hyderabad");
    Set<Map.Entry<String, String>> citySet = cityMap.entrySet();
    citySet.forEach((m)->System.out.println("key " + m.getKey() 
              + " value " + m.getValue()));
  }
}

Output

key CH value Chennai
key HD value Hyderabad
key MU value Mumbai
key ND value New Delhi

Here it can be seen that ConcurrentNavigableMap is sorted on the keys.

ConcurrentSkipListMap with Comparator

If you want sorting to be done in reverse order then you can pass a Comparator as a parameter when constructing a ConcurrentSkipListMap.

public class CSMDemo {
  public static void main(String[] args) {
    // With Comparator
    ConcurrentNavigableMap<String, String> cityMap = new ConcurrentSkipListMap<String, String>((String s1, String s2) -> s1.compareTo(s2));
    cityMap.put("ND", "New Delhi");
    cityMap.put("MU", "Mumbai");
    cityMap.put("CH", "Chennai");
    cityMap.put("HD", "Hyderabad");
    Set<Map.Entry<String, String>> citySet = cityMap.entrySet();
    citySet.forEach((m)->System.out.println("key " + m.getKey() 
             + " value " + m.getValue()));
  }
}

Output

key CH value Chennai
key HD value Hyderabad
key MU value Mumbai
key ND value New Delhi

Here it can be seen that elements in the ConcurrentNavigableMap are now sorted in reversed order.

Navigational methods in Java ConcurrentSkipListMap

As already mentioned ConcurrentSkipListMap in Java implements ConcurrentNavigableMap interface so it has many navigation methods returning the closest matches for given search targets. Let's see some of them in example code.

  • descendingKeySet()- Returns a reverse order NavigableSet view of the keys contained in this map.
  • floorEntry(K key)- Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.
  • headMap(K toKey)- Returns a view of the portion of this map whose keys are strictly less than toKey.
  • higherKey(K key)- Returns the least key strictly greater than the given key, or null if there is no such key.
import java.util.Iterator;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Set;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

public class CSMDemo {
  public static void main(String[] args) {
    ConcurrentNavigableMap<String, String> cityMap = new ConcurrentSkipListMap<String, String>();
    cityMap.put("ND", "New Delhi");
    cityMap.put("MU", "Mumbai");
    cityMap.put("CH", "Chennai");
    cityMap.put("HD", "Hyderabad");
    System.out.println("---- Traversing the map-----");
    Set<Map.Entry<String, String>> citySet = cityMap.entrySet();
    // using for-each loop in Java 8
    citySet.forEach((m)->System.out.println("key " + m.getKey() + 
            " value " + m.getValue()));
        
    NavigableSet<String> reverseKeys = cityMap.descendingKeySet();
    // using iterator
    Iterator<String> itr = reverseKeys.iterator();
    System.out.println("---- Map keys in reverse order-----");
    while(itr.hasNext()){
      System.out.println("Key " + itr.next());
    }
        
    System.out.println("---- Floor entry-----");
    
    Map.Entry<String, String> tempMap = cityMap.floorEntry("II");
    System.out.println(tempMap);
        
    System.out.println("---- Head Map-----");
    ConcurrentNavigableMap<String, String> map = cityMap.headMap("MU");
    Set<Map.Entry<String, String>> set = map.entrySet();
    // using for-each loop in Java 8
    set.forEach((m)->System.out.println("key " + m.getKey() + 
                " value " + m.getValue()));
    
    System.out.println("---- Higher entry-----");
        
    tempMap = cityMap.higherEntry("II");
    System.out.println(tempMap);
  }
}

Output

---- Traversing the map-----
key CH value Chennai
key HD value Hyderabad
key MU value Mumbai
key ND value New Delhi
---- Map keys in reverse order-----
Key ND
Key MU
Key HD
Key CH
---- Floor entry-----
HD=Hyderabad
---- Head Map-----
key CH value Chennai
key HD value Hyderabad
---- Higher entry-----
MU=Mumbai

DescendingKeySet returns the keys in reverse order.

floorEntry() method returns the greatest key less than or equal to the given key. Here key is provided as "II" if you see greatest key less than or equal to "II" is "HD". Note here that key provided should not be a key already present in the Map ("II" is not a key present in the Map).

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


Related Topics

  1. ConcurrentHashMap in Java With Examples
  2. Java CyclicBarrier With Examples
  3. Java ArrayBlockingQueue With Examples
  4. How to Sort Elements in Different Order in TreeSet
  5. Java Concurrency Interview Questions And Answers

You may also like-

  1. Java ReentrantLock With Examples
  2. Difference between HashMap and ConcurrentHashMap in Java
  3. How to Iterate a HashMap of ArrayLists of String in Java
  4. HashMap Vs LinkedHashMap Vs TreeMap in Java
  5. Method Reference in Java
  6. Difference Between Abstract Class And Interface in Java
  7. super Keyword in Java With Examples
  8. Creating Custom Exception Class in Java

Saturday, March 23, 2024

static Block in Java

Static block in Java is used for static initializations of a class. Consider a scenario where initialization of static variables requires some logic (for example, error handling or a for loop to fill a complex array). In such scenarios, simple assignment is inadequate.

In case of instance variables, initialization can be done in constructors, where exception handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

Refer Initializer block in Java to see another way to initialize instance variables.

static Block is Executed Only Once

A static block in a class is executed only once, when the class is first loaded, even before the main method.

Note that class can be loaded when you create an object of that class or when you access the static member of that class for the first time.

General form of the Java static block

static{
  // whatever code is needed for initialization goes here
}

static Block Java Example

public class StaticBlockDemo {
  // static blank final variable
  static final int i;
  static int b;
  //static block
  static {
   System.out.println("in static block");
   i = 5;
   b = i * 5;
   System.out.println("Values " + i + " " +  b);
  }
  
  public static void main(String[] args) {
     System.out.println(" in main method ");
  }
}

Output of the program

in static block
Values 5 25
in main method

It can be seen that main method is called only after executing the static block. In static block the static blank final variable is initialized. Also another static variable too is initialized with in the block after some computation.

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks in Java are called in the order that they appear in the source code.

Since static blocks are used to initialize the class variables so static blocks in Java are called before the constructor of the class.

public class StaticBlockDemo {
  // static blank final variable
  static final int i;
  static int b;
  //static block
  static {
   System.out.println("in static block");
   i = 5;
   b = i * 5;
   System.out.println("Values " + i + " " +  b);
  }
  
  StaticBlockDemo(){
   System.out.println("In constructor");
  }
  
  public static void main(String[] args) {
    System.out.println("in main method ");
    StaticBlockDemo sb = new StaticBlockDemo();
  }
  
  static {
   System.out.println("In another static block");
  }

}

Output

in static block
Values 5 25
In another static block
in main method 
In constructor

Java static block exception handling

static block can throw only RunTimeException, or there should be a try-catch block to catch checked exception.

static int i;
static int b;
static {
 System.out.println("in static block");
 try{
  i = 5;
  b = i * 5;
 }catch(Exception exp){
  System.out.println("Exception while initializing" + exp.getMessage());
  throw new RuntimeException(exp.getMessage()); 
}
 //System.out.println("Values " + i + " " +  b);
}

That's all for this topic static Block 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. static Keyword in Java With Examples
  2. static Method Overloading or Overriding in Java
  3. Interface Static Methods in Java
  4. Initializer block in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. super Keyword in Java With Examples
  2. this Keyword in Java With Examples
  3. Constructor overloading in Java
  4. Java Abstract Class and Abstract Method
  5. final Vs finally Vs finalize in Java
  6. How to Sort ArrayList of Custom Objects in Java
  7. Java Multithreading Interview Questions And Answers
  8. Java Stream API Examples

Friday, March 22, 2024

Java Record Class With Examples

In this tutorial you’ll learn about a new way of creating class using record keyword in Java which has become a feature from Java 16.

Many a time we create classes meant for storing data. Such Bean classes are not meant to be altered and consists of constructors and accessor methods (getters and setters) which are sufficient to make such classes act like "plain data carriers".

Here is an example of Person class with fields name, gender and age.

public class Person {
	private String name;
	private char gender;
	private int age;
	Person(String name, char gender, int age){
		this.name = name;
		this.gender = gender;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public char getGender() {
		return gender;
	}
	public int getAge() {
		return age;
	}
}

As you can see a lot of code is required just to create a class meant as a data carrier.

Record classes in Java are a way to create such classes with just a single line of code.

Java record keyword

record keyword in Java is a new kind of type declaration which helps in creating a class.

You just need to declare a record with a name and a description of its contents.

The appropriate constructor, accessors, equals, hashCode, and toString methods are generated automatically. For example, Person class as described above can be defined using record as given below.

public record Person(String name, char gender, int age) {}

That’s all you need to create a Person class. A record consists of a name (Person in our example) and a list of the record's components (which in this example are String name, char gender and int age).

This Person class created using record generates the following members automatically.

  1. All fields specified in the record are declared as private final fields. So in Person record class given fields will be declared automatically.
  2. public accessors methods for the fields having the same name and type as field name.
  3. A constructor having the same name as the name used with record keyword. Constructor parameters are same as the record’s component list.
  4. Implementations of the equals() and hashCode() methods
  5. An implementation of the toString method that includes the string representation of all the record class's components, with their names.

Creating instance of record

As record classes are just special kinds of classes, you create a record object with the new keyword same way you create an instance of normal class.

public class PersonMain {

	public static void main(String[] args) {
		Person person = new Person("Dinesh", 'M', 32);
		System.out.println("Name- " + person.name());
		System.out.println("Gender- " + person.gender());
		System.out.println("Age- " + person.age());
	}
}

Output

Name- Dinesh
Gender- M
Age- 32

Important points about record

1. In order to have a better idea about generated class by using record keyword let’s use javap to disassemble class file.

D:\NETJS\NetJS_2017\JavaWS>javap Person.class
Compiled from "Person.java"
public final class com.netjstech.Person extends java.lang.Record {
  public com.netjstech.Person(java.lang.String, char, int);
  public java.lang.String name();
  public char gender();
  public int age();
  public final java.lang.String toString();
  public final int hashCode();
  public final boolean equals(java.lang.Object);
}
You can see that the generated class is final which means it can’t be subclassed.

2. Any class created using record extends java.lang.Record which is the common base class of all Java language record classes.

3. If you want to add your own constructor in a record class that is permissible.

public record Person(String name, char gender, int age) {
  public Person(String name, char gender, int age){
    if(name.isBlank() || age < 1) {
      throw new java.lang.IllegalArgumentException("Name can't be left blank and age should be atleast 1");
    }
    this.name = name;
    this.gender = gender;
    this.age = age;
  }
}

4. You can also add a compact constructor where the constructor’s signature is derived from the record’s components. For example constructor as shown above can also be written in the following compact form.

public record Person(String name, char gender, int age) {
  public Person{
    if(name.isBlank() || age < 1) {
      throw new java.lang.IllegalArgumentException("Name can't be left blank and age should be atleast 1");
    }
  }
}

5. You can declare static fields, static initializers, and static methods in a record class, and they behave as they would in a normal class.

public record Person(String name, char gender, int age) {
	static String country;
	static {
		country = "India";
	}
	public static void displayCountry() {
		System.out.println("Country- " + country);
	}
}
public class PersonMain {

	public static void main(String[] args) {
		Person person = new Person("Dinesh", 'M', 32);
		System.out.println(person);
		Person.displayCountry();
	}
}

Output

Person[name=Dinesh, gender=M, age=32]
Country- India

6. You cannot declare instance variables or initializer blocks in a record class.

public record Person(String name, char gender, int age) {
	String country;
	// initializer block
	{
		country = "India";
	}
}
This results in compile time error-

User declared non-static fields country are not permitted in a record

7. You can add instance methods in a record class.

public record Person(String name, char gender, int age) {
	public void displayPersonDetails() {
		System.out.println("Name- " + name());
		System.out.println("Gender- " + gender());
		System.out.println("Age- " + age());
	}
}
public class PersonMain {

	public static void main(String[] args) {
		Person person = new Person("Dinesh", 'M', 32);
		person.displayPersonDetails();
	}
}

Output

Name- Dinesh
Gender- M
Age- 32

8. Java record was added as a preview feature in Java 14 (JEP 359). Became a finalized feature in Java 16 (JEP 395).

That's all for this topic Java Record Class With 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. Java Sealed Classes and Interfaces
  2. Private Methods in Java Interface
  3. Var type in Java - Local Variable Type Inference
  4. Effectively Final in Java 8
  5. Switch Expressions in Java 12

You may also like-

  1. Primitive Type Streams in Java Stream API
  2. Fix Scanner.nextLine() Skipping Input After Another next Methods
  3. Array in Java With Examples
  4. Arrange Non-Negative Integers to Form Largest Number - Java Program
  5. Angular Disable Button Example
  6. Angular Template-Driven Form Validation Example
  7. Spring MVC Pagination Example Using PagedListHolder
  8. Python Exception Handling - try,except,finally

Thursday, March 21, 2024

Java Stream - count() With Examples

In this tutorial you’ll learn about the count() method in the Java Stream API with the help of few examples.

count() method in Java

count() method returns the count of elements in the stream.

Syntax of count() method-

long count()

Some important points about count() method-

  1. It is a special case of a reduction operation which means it takes a sequence of input elements and reduce them into a single summary result.
  2. It is a terminal operation which means after count() operation the stream pipeline is considered consumed, and can no longer be used.

count() method Java examples

1. In the first example count() is used to get the count of elements in a List where List is used as a stream source.

public class StreamCountDemo {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(7, 5, 18, -11, 22, -8);
    long elementCount = numList.stream().count();
    System.out.println("Count of elements- " + elementCount);  
  }
}

Output

Count of elements- 6

2. Since count is a terminal operation so stream is considered closed after count operation but before count, intermediate operations like filter can be used to filter out certain elements and then get the count of the resulting stream. For example if we want count of positive elements in a list.

public class StreamCountDemo {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(7, 5, 18, -11, 22, -8);
    long elementCount = numList.stream().filter(n -> n > 0).count();
    System.out.println("Count of elements- " + elementCount);  
  }
}

Output

Count of elements- 4

3. In the following example count is used to get the count of employees having salary greater than 10000.

Employee class

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
  @Override
  public String toString() {
      return "Emp Id: " +  getEmpId() + " Name: " + getName() + " Age: " + getAge();
  }
}
public class StreamCountDemo {

  public static void main(String[] args) {
    List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                new Employee("E002", 35, "Shelly", 'F', 7000), 
                new Employee("E003", 40, "Remington", 'M', 5000), 
                new Employee("E004", 37, "Bianca", 'F', 11000),
                new Employee("E005", 35, "Dominic", 'M', 7000), 
                new Employee("E006", 28, "Amanda", 'F', 14000));
    long elementCount = empList.stream().filter(e -> e.getSalary() > 10000).count();
    System.out.println("Count of elements- " + elementCount);  
  }
}

Output

Count of elements- 2

That's all for this topic Java Stream - count() With 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. Java Stream - boxed() With Examples
  2. Java Stream - sorted() With Examples
  3. Java Stream - distinct() With Examples
  4. Parallel Stream in Java Stream API
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. Type Erasure in Java Generics
  2. SerialVersionUID And Versioning in Java Serialization
  3. Difference Between CountDownLatch And CyclicBarrier in Java
  4. Difference Between StackOverflowError and OutOfMemoryError in Java
  5. Docker Tutorial: Introduction to Docker
  6. Benefits, Disadvantages And Limitations of Autowiring in Spring
  7. Spring MVC JSON as Response Example
  8. Angular Access Control CanActivate Route Guard Example