Tuesday, June 20, 2023

Java Program to Print Line Numbers With Lines in Java

If you want to print line number along with the lines of the file you can do that using LineNumberReader in Java.

LineNumberReader class has a method getLineNumber() that gives the current line number of the file. So, wrap your Reader object with in the LineNumberReader to get this extra functionality to get line numbers.

Printing lines of the file with line number Java code

If you have a file named abc.txt with the following content:

This is a test file.
Line number reader is used to read this file.
This program will read all the lines.
It will give the count.

Then you can get the line numbers using the following Java code.

 
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

public class LineNumberDemo {
 public static void main(String[] args) {
  LineNumberReader reader = null;
    try {
      reader = new LineNumberReader(new FileReader(new File("F:\\abc.txt")));
      String str;
      // Read file till the end
      while ((str = reader.readLine()) != null){
        System.out.println(reader.getLineNumber() + "- " + str);
      }         
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally { 
      if(reader != null){
        try {
          reader.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}

Output

 
1- This is a test file.
2- Line number reader is used to read this file.
3- This program will read all the lines.
4- It will give the count.

That's all for this topic Java Program to Print Line Numbers With Lines 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. How to Read File From The Last Line in Java
  2. Reading Delimited File in Java Using Scanner
  3. Reading File in Java Using Files.lines And Files.newBufferedReader
  4. Writing a File Asynchronously Java Program
  5. How to Count Lines in a File in Java

You may also like-

  1. How to Create Password Protected Zip File in Java
  2. How to Read Input From Console in Java
  3. Convert int to String in Java
  4. How to Find Last Modified Date of a File in Java
  5. JavaScript Array slice() method With Examples
  6. Run Python Application in Docker Container
  7. Spring MVC Java Configuration Example
  8. Custom Async Validator in Angular Template-Driven Form

Monday, June 19, 2023

Passing Object of The Class as Parameter in Python

In this post we’ll see how to pass object of the class as parameter in Python.

Passing object as parameter

In the example there are two classes Person and MyClass, object of class Person is passed as parameter to the method of class MyClass.

class MyClass():
  def my_method(self, obj):
    print('In my_method method of MyClass')
    print("Name:", obj.name)
    print("Age:", obj.age)
In MyClass there is one method my_method() which takes self as one of the argument and another argument is obj, that is where I intend to pass an object of Person class.
 
from MyClass import MyClass
class Person:
  def __init__(self, name, age):
    print('init called')
    self.name = name
    self.age = age

  def display(self):
    print('in display')
    print("Name-", self.name)
    print("Age-", self.age)
    # object of class MyClass
    obj = MyClass()
    # passing person object to
    # method of MyClass (self = person here)
    obj.my_method(self)

person = Person('John', 40)
person.display()
In class Person, MyClass is also used so that is imported.
from MyClass import MyClass
In method display() object of MyClass is created.
obj = MyClass()
Then the my_method() method of class MyClass is called and object of Person class is passed as parameter.
 # passing person object to
 # method of MyClass (self = person here)
 obj.my_method(self)
On executing this Python program you get output as following.
init called
in display
Name- John
Age- 40
In my_method method of MyClass
Name: John
Age: 40

That's all for this topic Passing Object of The Class as Parameter in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Class And Object in Python
  2. Constructor in Python - __init__() function
  3. Multiple Inheritance in Python
  4. Method Overloading in Python
  5. Abstract Class in Python

You may also like-

  1. Accessing Characters in Python String
  2. Python Conditional Statement - if, elif, else Statements
  3. Python Program to Display Armstrong Numbers
  4. JVM Run-Time Data Areas - Java Memory Allocation
  5. Linear Search (Sequential Search) Java Program
  6. Passing Arguments to getBean() Method in Spring
  7. Connection Pooling With Apache DBCP Spring Example
  8. Word Count MapReduce Program in Hadoop

Sunday, June 18, 2023

Spring NamedParameterJdbcTemplate Select Query Example

In the post Spring NamedParameterJdbcTemplate Insert, Update And Delete Example I have already discussed how NamedParameterJdbcTemplate can be used for inserting and updating data in the DB. In this post we’ll see how to fetch data from DB using named parameters i.e. a select query example using NamedParameterJdbcTemplate in Spring. Main intention to have it as a separate post is to discuss callback part in detail.

In the post Data access in Spring framework it has been discussed in detail how Spring framework provides templates to manage the fixed part and use call back to handle the variable part. Fetching data from DB using select query has, as usual, the fixed part like getting connection, cleaning up, handling exception but at the same time Spring framework does need help to map the fetched data to the model. That’s where callback comes into picture.


NamedParameterJdbcTemplate in Spring

Spring framework provides NamedParameterJdbcTemplate class which adds support for programming JDBC statements using named parameters, as opposed to programming JDBC statements using only classic placeholder ('?') arguments.

Here one thing to note is NamedParameterJdbcTemplate class wraps a JdbcTemplate, and delegates to the wrapped JdbcTemplate to do much of its work.

Technologies used

  • Spring 5.0.4
  • Apache DBCP2
  • MYSQL 5.1.39
  • Java 8
  • Apache Maven 3.3.3

Maven Dependencies

If you are using maven then you can provide dependencies in your pom.xml.

With all the dependencies your pom.xml should look something like this-

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.netjs.prog</groupId>
  <artifactId>maven-spring</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>maven-spring</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>5.0.4.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    
     <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>
    
    <!-- Spring JDBC Support -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    
   <!-- MySQL Driver -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.39</version>
    </dependency>
    
    <!--  Apache DBCP connection pool -->
    <dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-dbcp2</artifactId>
       <version>2.1</version>
    </dependency>
  </dependencies>
</project>

Alternatively you can download the jars and add them to the class path.

Spring NamedParameterJdbcTemplate Select Query Example

Note that NamedParameterJdbcTemplate needs a DataSource in order to perform its management of fixed part like getting a DB connection, cleaning up resources.

In this post Apache DBCP is used which provides pooled datasource and MYSQL is used as the back end.

Database table

DB table used for this example is called employee with the columns id, name and age in the MYSQL DB. Column id is configured as auto increment checked so no need to pass id from your query as DB will provide value for it.

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(35) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

Configuring datasource dependency

First thing is to set up DataSource as a bean. I have used properties file to configure datasource where all the properties are there in the db.properties file.

<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value = "${db.driverClassName}" />
    <property name="url" value = "${db.url}" />
    <property name="username" value = "${db.username}" />
    <property name="password" value = "${db.password}" />
    <property name="initialSize" value = "${pool.initialSize}" />
</bean>

Where as db.properties file which is under the config folder has all the properties.

db.properties

db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/netjs
db.username=
db.password=
pool.initialSize=5

Description for the properties used here is as-

driver class name is the JDBC driver for the DB used. Since MYSQL is used here so the jdbc driver for the same (com.mysql.jdbc.Driver) is provided.

Url – You need to provide url to access your DB server. I have created a schema called netjs and DB is running on the same system so url is jdbc:mysql://localhost:3306/netjs.

Username and password for the DB.

IntialSize is the initial size of the connection pool. It is given as 5 so initially 5 connections will be created and stored in the pool.

To use properties file you need to put following configuration in your XML.

<context:property-placeholder location="classpath:config/db.properties" />

Spring NamedParameterJdbcTemplate configuration

DataSource bean has to be provided as a reference in NamedParameterJdbcTemplate.

<bean id="namedJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">  
    <constructor-arg ref="dataSource"></constructor-arg> 
</bean>

Java Classes

Since Spring always promotes to use interfaces and there is also a JEE design pattern for database layer called DAO which also says the same thing- Separate low level data access code from the business layers.

So we have a EmployeeDAO interface with insert, update and delete methods and its implementing class EmployeeDAOImpl. There is also a model class Employee with all the getters/setters.

Employee.java class

public class Employee {
 private int empId;
 private String empName;
 private int age;
 
 public int getEmpId() {
  return empId;
 }
 public void setEmpId(int empId) {
  this.empId = empId;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

EmployeeDAO interface

public interface EmployeeDAO {
    
    public List<Employee> findAllEmployees();
    
    public Employee findEmployee(int empId);
    
}

EmployeeDAOImpl class

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.netjs.dao.EmployeeDAO;
import org.netjs.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDAOImpl implements EmployeeDAO {
  private NamedParameterJdbcTemplate namedJdbcTemplate; 
  
  final String SELECT_BY_ID_QUERY = "SELECT id, name, age from EMPLOYEE where id = :id";
  final String SELECT_ALL_QUERY = "SELECT id, name, age from EMPLOYEE";
    
  @Autowired
  public EmployeeDAOImpl(NamedParameterJdbcTemplate namedJdbcTemplate){
    this.namedJdbcTemplate = namedJdbcTemplate;
  }

  @Override
  public List<Employee> findAllEmployees() {
    return this.namedJdbcTemplate.query(SELECT_ALL_QUERY, new EmployeeMapper());
  }

  @Override
  public Employee findEmployee(int empId) {
    return this.namedJdbcTemplate.queryForObject(SELECT_BY_ID_QUERY, new MapSqlParameterSource(
       "id", empId), new EmployeeMapper());
  }
    
  private static final class EmployeeMapper implements RowMapper<Employee> {
    public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
      Employee emp = new Employee();
      emp.setEmpId(rs.getInt("id"));
      emp.setEmpName(rs.getString("name"));
      emp.setAge(rs.getInt("age"));
      return emp;
    }
  }
}
If you have more than one named parameter you can also use a hashMap or create a chain of addValue() methods with a MapSqlParameterSource class object. Refer Spring NamedParameterJdbcTemplate Insert, Update And Delete Example to see an example.

Notice how you are not writing any code for getting or closing connection, exception handling. All that fixed part is managed by the template class.

If there is any SQLException thrown that is also caught by JdbcTemplate and translated to one of the DataAccessException and rethrown.

Explanation of RowMapper callbacks

Main thing to demonstrate in this Spring NamedParameterJdbcTemplate select query example is how callback works. Here template callbacks are used to query the DB and then map the returned result set to the model (Employee) object(s).

If you have noticed in findEmployee(int empId) method queryForObject method of JdbcTemplate is used which takes 3 parameters-

  • SQL query String.
  • Object of type SQLParameterSource that is where MapSqlParameterSource object is passed which stores all the named parameters to be bound to the query.
  • RowMapper object that maps a single result row to a Java object via a RowMapper.

Whereas in findAllEmployees() method query method is used which takes only two parameters–

  • SQL query String
  • RowMapper object

Main thing here is RowMapper object which in this example is the object of class EmployeeMapper implementing the RowMapper interface.

RowMapper interface has a single method mapRow which takes two arguments-

  • ResultSet- A table of data representing a database result set.
  • int- the number of the current row
and this method returns the result object for the current row.

For every row in the result set, JdbcTemplate calls the mapRow() method of the RowMapper interface implementing class. Arguments passed are ResultSet and an integer which is the number of the current row in the result set. Using that row number cursor is moved to the given row in the result set.

Full XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    
   <context:component-scan base-package="org.netjs.daoimpl" />
    <!--  For reading properties files --> 
    <context:property-placeholder location="classpath:config/db.properties" />
    
    <bean id="namedJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">  
        <constructor-arg ref="dataSource"></constructor-arg> 
    </bean> 
    <!-- <bean id="employeeDAO" class="org.netjs.daoimpl.EmployeeDAOImpl">
        <property name="namedJdbcTemplate" ref="namedJdbcTemplate"></property>  
    </bean> -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value = "${db.driverClassName}" />
        <property name="url" value = "${db.url}" />
        <property name="username" value = "${db.username}" />
        <property name="password" value = "${db.password}" />
        <property name="initialSize" value = "${pool.initialSize}" />
    </bean>

</beans>

If you are not using automatic configuration, then you can uncomment the bean definition for the EmployeeDAO.

Test class

You can use the following code in order to test the code-

import java.util.List;
import org.netjs.dao.EmployeeDAO;
import org.netjs.model.Employee;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

  public static void main(String[] args) {
    
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
     ("appcontext.xml");
    EmployeeDAO dao = (EmployeeDAO)context.getBean("employeeDAOImpl");  
    // finding by ID       
    Employee emp = dao.findEmployee(5);
    System.out.println("Name - "+ emp.getEmpName() + " Age - " + emp.getAge());  
    // finding all       
    List<Employee> empList = dao.findAllEmployees();
    System.out.println("Name - "+ empList.get(3).getEmpName() + 
      " Age - " + empList.get(3).getAge());
  }
}

That's all for this topic Spring NamedParameterJdbcTemplate Select Query Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring JdbcTemplate Select Query Example
  2. Spring JdbcTemplate Insert, Update And Delete Example
  3. Configuring DataSource in Spring Framework
  4. Spring Component Scan to Automatically Discover Beans
  5. How to Read Properties File in Spring Framework

You may also like-

  1. registerShutdownHook() Method in Spring Framework
  2. BeanFactoryAware Interface in Spring Framework
  3. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation
  4. Abstraction in Java
  5. String in Java Tutorial
  6. LinkedHashMap in Java With Examples
  7. Java StampedLock With Examples
  8. ConcurrentHashMap in Java With Examples

Saturday, June 17, 2023

Reading Delimited File in Java Using Scanner

In this post we'll see how to read delimited file (like CSV) in Java using Scanner class.

A Scanner, when reading input, breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

The scanner can also use delimiters other than whitespace. Scanner class has useDelimiter() method which can be used to change default delimiter. There are two overloaded useDelimiter() methods.

  • useDelimiter(Pattern pattern)- Sets this scanner's delimiting pattern to the specified pattern.
  • useDelimiter(String pattern)- Sets this scanner's delimiting pattern to a pattern constructed from the specified String.

Java program to read CSV file using Scanner

Let's see an example where Scanner class is used to read a CSV file.

If there is a CSV file with following data-

Pride And Prejudice,Jane Austen,20.76
The Murder of Roger Ackroyd,Agatha Christie,25.67
Atlas Shrugged,Ayn Rand,34.56
Gone with the Wind,Margaret Mitchell,36.78

And you want to read and parse the line so that you have Book name, author and price as separate strings.

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ScanDelimited {

 public static void main(String[] args) {
  // CSV file
  File file = new File("G:\\Temp.csv");
  Scanner sc = null;
  try {
   sc = new Scanner(file);
   // Check if there is another line of input
   while(sc.hasNextLine()){
    String str = sc.nextLine();
    parseLine(str);
   }
   
  } catch (IOException  exp) {
   // TODO Auto-generated catch block
   exp.printStackTrace();
  }
  
  sc.close();
 }
 
 private static void parseLine(String str){
  String book, author, price;
  Scanner sc = new Scanner(str);
  sc.useDelimiter(",");

  // Check if there is another line of input
  while(sc.hasNext()){
   book = sc.next();
   author = sc.next();
   price = sc.next();
   System.out.println("Book - " + book + " Author - " + author + 
     " Price - " + price);  
  }
  sc.close();
 }
}

Output

Book - Pride And Prejudice Author - Jane Austen Price - 20.76
Book - The Murder of Roger Ackroyd Author - Agatha Christie Price - 25.67
Book - Atlas Shrugged Author - Ayn Rand Price - 34.56
Book - Gone with the Wind Author - Margaret Mitchell Price - 36.78

Java program to read pipe (|) delimited file using Scanner

If you have a file where pipe is used as delimiter then you can specify that as delimiter with useDelimiter() method to read the file.

Data

Pride And Prejudice|Jane Austen|20.76
The Murder of Roger Ackroyd|Agatha Christie|25.67
Atlas Shrugged|Ayn Rand|34.56
Gone with the Wind|Margaret Mitchell|36.78
package org.netjs.examples1;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ScanDelimited {

 public static void main(String[] args) {
  // delimited file
  File file = new File("G:\\abc.txt");
  Scanner sc = null;
  try {
   sc = new Scanner(file);
   // Check if there is another line of input
   while(sc.hasNextLine()){
    String str = sc.nextLine();
    parseLine(str);
   }
   
  } catch (IOException  exp) {
   // TODO Auto-generated catch block
   exp.printStackTrace();
  }
  
  sc.close();
 }
 
 private static void parseLine(String str){
  String book, author, price;
  Scanner sc = new Scanner(str);
  sc.useDelimiter("[|]");

  // Check if there is another line of input
  while(sc.hasNext()){
   book = sc.next();
   author = sc.next();
   price = sc.next();
   System.out.println("Book - " + book + " Author - " + author + 
     " Price - " + price);  
  }
  sc.close();
 } 
}

Output

Book - Pride And Prejudice Author - Jane Austen Price - 20.76
Book - The Murder of Roger Ackroyd Author - Agatha Christie Price - 25.67
Book - Atlas Shrugged Author - Ayn Rand Price - 34.56
Book - Gone with the Wind Author - Margaret Mitchell Price - 36.78

That's all for this topic Reading Delimited File in Java Using Scanner. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Reading File in Java Using Scanner
  2. Reading File in Java Using Files.lines And Files.newBufferedReader
  3. How to Read Input From Console in Java
  4. How to Read File From The Last Line in Java
  5. Creating Tar File And GZipping Multiple Files in Java

You may also like-

  1. Java Program to Reverse a Number
  2. Producer-Consumer Java Program Using wait notify
  3. Difference Between Two Dates in Java
  4. If Given String Sub-Sequence of Another String in Java
  5. finally Block in Java Exception Handling
  6. Callable and Future in Java With Examples
  7. Difference between HashMap and HashTable in Java
  8. Dependency Injection Using factory-method in Spring

Friday, June 16, 2023

How to Use ngFor and ngIf in Same Element in Angular

In Angular if you want to use two structural directives like *ngFor and *ngIf in the same element (like <div>, <tr>) that results in an error.

Can't have multiple template bindings on one element. Use only one attribute prefixed with *

How to use ngFor and ngIf on same element

It is very common to show only specific records while looping i.e. having ngIf to test a condition with in a ngFor loop or to loop elements only when a condition is true i.e. having ngFor within ngIf condition.

For example let’s say you have to iterate through Region objects using ngFor showing only those records where sales is greater than 200, writing it as given below results in error as both *ngFor and *ngIf are with in the same <tr> element.

<div class="container">
  <table class="table table-sm table-bordered m-t-4 table-striped">
    <thead>
      <tr>
        <th>Region</th>
        <th>Manager</th>
        <th>Sales (in millions)</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let region of regions" *ngIf="region.sales > 200">       
        <td>{{region.region}}</td>
        <td>{{region.regionalManager}}</td>               
        <td>{{region.sales}}</td>
      </tr>
    </tbody>
  </table>
</div>

Thursday, June 15, 2023

Lambda Expressions in Java 8

Lambda expressions in Java (also known as closures) are one of the most important feature added in Java 8. Java lambda expressions provide a clear and elegant way to represent a single abstract method interface (Functional interface) using an expression.


What is a functional interface

In order to know Lambda expressions better it is very important to have a good understanding of two terms- lambda expression itself and functional interface. Here is a little primer about functional interfaces.

A functional interface is an interface with only one abstract method. A functional interface is also known as SAM type where SAM stands for (Single Abstract Method). An example of functional interface would be Runnable interface which has only one method run().

Please note that from Java 8 it is possible for an interface to have default methods and static methods thus the stress on "only one abstract method".

Also a new annotation @FunctionalInterface has been added in Java 8, all the functional interfaces can be annotated with this annotation to ensure that they have only single abstract method.

functional interface Example

interface IMyInterface {
  int getValue();
}

In interface IMyInterface there is a single abstract method getValue() (note that in an interface methods are implicitly abstract).

See Functional Interfaces in Java for detailed post about functional interfaces.

Java lambda expressions

Lambda expression in Java is an instance of a functional interface and provides implementation of the single abstract method defined by the functional interface.

Lambda Expression Syntax

A new operator has been introduced in Java for Lambda expressions.

(arg1, arg2, ..) -> body

Here you can see a new arrow operator (->) or lambda operator which divides the lambda expression into two parts.

Left side specifies parameters required by the lambda expression. Parameters are optional, if no parameters are needed an empty parenthesis can be given. Even type of the parameters is not required as compiler, in most of the cases, is able to infer type of the parameters from the context in which it is used.

Right side known as lambda body specifies the logic of the lambda expression.

Why Lambda expressions in Java

Now when we have an idea about lambda expressions and functional interfaces let's try to understand how does lambda expressions help in making your code more compact.

Most used use case for anonymous class is to implement an interface that contains only one method. This is usually done when you are trying to pass functionality as an argument to another method.

For example if you have a List of objects of type Person and you want to sort them on the basis of first name using a Comparator. In that case you need to implement compare() method of the Comparator interface. Usually that is done by implementing Comparator as an anonnymous class. So what you are doing is to pass the functionality to compare objects as an argument to Collections.sort() method.

Collections.sort(personList, new Comparator<Person>() {
  public int compare(Person a, Person b) {
    return a.getFirstName().compareTo(b.getFirstName());
  }
});
Java lambda expression also enables you to do the same thing like-
  • Passing functionality as method argument.
  • Passing code as data.

Lambda expressions can only be used to implement functional interfaces (interface with single abstract method) and lambda expressions let you express these instances of single-method classes more compactly than by using anonymous class.

For example if you have to implement the same Comparator as used above as a lambda expression then it can be done more compactly as-

Collections.sort(personList, (Person a, Person b) -> 
            a.getFirstName().compareTo(b.getFirstName()));
Type can be inferred from the surrounding context so you don't even need to define the type of the parameters.
Collections.sort(personList, (a, b) -> 
            a.getFirstName().compareTo(b.getFirstName()));

Here you can see that the functionality for sorting (implementation of compare method of the Comparator) is passed as method argument.

Java lambda expression examples

Let's see some examples of the lambda expressions in Java-

1. A very simple lambda expression.

() -> 7; 

This lambda expression takes no parameter, that's why empty parenthesis and returns the constant value 7.

If we have to write the equivalent Java method then it will be something like this-

int getValue(){
  return 7;
}

2. Lambda expressions with 2 parameters.

// concatenating two strings, it has 2 string parameters
// and they are concatenated in lambda body
(String s1, String s2) -> s1+s2;

3. Lambda expression to test if the given number is odd or not.

// Lambda expression to test if the given number is odd or not
n -> n % 2 != 0;

4. Lambda expression to display passed argument.

// Prints the passed string s to the console and returns void
(String s) -> { System.out.println(s); };

5. Complete Java Lambda expression example.

interface IMyInterface {
  int getValue();
}

public class LambdaExpressionDemo {
  public static void main(String[] args) {
    // reference of the interface
    IMyInterface objRef;
    // Lambda expression
    objRef = () -> 7;
    System.out.println("Value is " + objRef.getValue());
    // Another lambda expression using the same interface reference 
    objRef = () -> 7 * 5;
    System.out.println("Value is " + objRef.getValue());
    // This line will give compiler error as target type 
    // can't be inferred 
    objref = () -> "11";
  }
}

Output

Value is 7
Value is 35

Here we have an interface IMyInterface with one method getValue() whose return type is int. Since there is only one abstract method in the interface so IMyInterface is a functional interface.

In this program it can be seen how lambda expression () -> 7 is compatible with the abstract method. Return type is int and there is no method parameter.
If you uncomment the line () -> "11"; it will give compiler error The target type of this expression must be a functional interface as in this case return type is string which is not compatible with the return type of the abstract method, lambda expression is implementing.

Also notice that the same functional interface reference is used to execute 2 lambda expressions
objRef = () -> 7; and objRef = () -> 7 * 5;
Since both of the lambda expressions are compatible with the target type so both of them can be assigned to the same reference (Does it remind you of run time polymorphism?). That's why Lambda Expression is a Poly Expression.

6. Java Lambda expression with a parameter example.

interface IMyInterface {
  boolean test(int n);
}

public class LambdaExpressionDemo {
  public static void main(String[] args) {
    IMyInterface objRef;
    // Lambda expression
    objRef = n -> (n % 2) == 0;
    System.out.println("4 is even " + objRef.test(4)); 
    System.out.println("3 is even " + objRef.test(3)); 
  }
}

Output

4 is even true
3 is even false

Here we need to note certain points-

n -> (n % 2) == 0;

In this lambda expression type is not specified explicitly as int, type is inferred from the context in which the lambda expression is executed, though type can be given explicitly too.

int n -> (n % 2) == 0;

This lambda expression is also valid.

Also parenthesis around the parameter is omitted, in case of single parameter it is not necessary to enclose the parameter with parenthesis. Again it won't be invalid to do that, so (n) -> (n % 2) == 0; or (int n) -> (n % 2) == 0; both are valid.

In case of more than one parameter too type can be inferred so
(int x, int y) -> x+y; or (x, y) -> x + y;
both of these are valid if used in a correct context.

One important point here is we can't have lambda expression where type for only one of the parameter is explicitly declared.

// Invalid lambda expression
(int x, y) -> x + y; 

See Lambda Expression Examples in Java for more examples of lambda expression.

Target type of Lambda expressions in Java

Lambda expression is an instance of the functional interface thus the functional interface specifies its target type.

Lambda supports "target typing" which infers the object type from the context in which it is used. To infer that object type from the context-

  • The parameter type of the abstract method and the parameter type of the lambda expression must be compatible. For Example, if the abstract method in the functional interface specifies one int parameter, then the lambda should also have one int parameter explicitly defined or implicitly inferred as int by the context.
  • Its return type must be compatible with the method's type.
  • Lambda expression can throw only those exceptions which are acceptable to the method.

Target typing is used in a number of contexts including the following-

  • Variable declarations
  • Assignments
  • Return statements
  • Array initializers
  • Method or constructor arguments
  • Lambda expression bodies

Block lambda expression in Java

Till now all the examples we have seen are single expression lambda, we also have a second type of lambda expressions known as "block lambda" where the right side of the lambda expression is a block of code.

Let's see an example, here with in the lambda expression we have a block of code for counting the words in a string without using any String function.

@FunctionalInterface
interface IMyInterface {
  int doCount(String str);
}

public class LambdaExpressionDemo {
  public static void main(String[] args) {
    // Lambda expression
    IMyInterface objRef = (str) -> {
      int c = 0;
      char ch[]= new char[str.length()];
      for(int i = 0; i < str.length(); i++){
          ch[i] = str.charAt(i);
          if(((i > 0) && (ch[i] != ' ') && (ch[i-1] == ' ')) || 
          ((ch[0] != ' ') && (i == 0)))
              c++;
      }
      return c;
    };    
    System.out.println("Words in the string " + objRef.doCount("Lambda Expression in Java"));    
  }
}

Output

Words in the string 4

Note here that functional interface is annotated with a @FunctionalInterface annotation, this is a new annotation added in Java 8 to be used with functional interface.

See Functional interface annotation in Java 8 for detailed post about @FunctionalInterface annotation.

Points to note-

  • Lambda expression is an instance of a functional interface and provides implementation of the single abstract method defined by the functional interface.
  • The lambda expression signature must be the same as the functional interface method's signature, as the target type of the lambda expression is inferred from that context.
  • A lambda expression can throw only those exceptions or the subtype of the exceptions for which an exception type is declared in the functional interface method's throws clause.
  • The parameter list of the lambda expression can declare a vararg parameter: (int ... i) -> {};
  • A Lambda Expression Is a Poly Expression- The type of a lambda expression is inferred from the target type thus the same lambda expression could have different types in different contexts. Such an expression is called a poly expression.

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


Related Topics

  1. Java Lambda Expression as Method Parameter
  2. Java Lambda Expression And Variable Scope
  3. Method Reference in Java
  4. Java Stream API Tutorial
  5. Java Lambda Expressions Interview Questions And Answers

You may also like-

  1. How to Fix The Target Type of This Expression Must be a Functional Interface Error
  2. How to Resolve Local Variable Defined in an Enclosing Scope Must be Final or Effectively Final Error
  3. Java Exception Handling Tutorial
  4. Multi-Catch Statement in Java Exception Handling
  5. Covariant Return Type in Java
  6. static Import in Java With Examples
  7. How HashMap Works Internally in Java
  8. Difference Between yield And sleep in Java Multi-Threading

Wednesday, June 14, 2023

Angular ngIf Directive With Examples

Angular provides some of the built-in directives to perform the most common tasks in web application development. Angular ngIf directive is used to conditionally include or remove an element in the HTML document.

If the expression used with the ngIf directive evaluates to true, element is included in the DOM if expression evaluates to false then the element is removed from the DOM.

Here are some examples of ngIf directive-

1. <div *ngIf="true"></div>

Element is always displayed.

2. <div *ngIf="false"></div>

Element is never displayed.

3. <div *ngIf="x > y"></div>

Element is displayed if x is greater than y.

4. <div *ngIf="myFunc()"></div>

Element is displayed if myFunc returns true.


ngIf is a structural directive

As you would have seen in the above examples, asterisk (*) precedes the ngIf directive attribute which means it is a structural directive. Structural directives are responsible for HTML layout. They change the DOM's structure, typically by adding, removing, or manipulating elements.

Internally Angular translates the *ngIf attribute into a <ng-template> element. If you have a statement as given below

<div *ngIf="user" class="name">{{user.name}}</div>

It is translated into a <ng-template> element, wrapped around the host element, like this.

<ng-template [ngIf]="user">
  <div class="name">{{user.name}}</div>
</ng-template>

Tuesday, June 13, 2023

How to Count Lines in a File in Java

Sometimes you just want to count the number of lines in a file, rather than reading the content of file. The easiest way, I feel, is to use LineNumberReader for counting the lines in a file in Java.

LineNumberReader class has a method getLineNumber() that gives the current line number of the file. So the logic for counting the number of lines in a file is as follows-

Using the LineNumberReader read all the lines of the files until you reach the end of file. Then use getLineNumber() method to get the current line number.

Using the getLineNumber() method you can also display line numbers along with the lines of the file.

Java program to count number of lines in a file

If you have a file with lines as follows-

This is a test file.
Line number reader is used to read this file.
This program will read all the lines.
It will give the count.

Then you can get the count of lines using the following code-

 
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

public class LineNumberDemo {
  public static void main(String[] args) {
    LineNumberReader reader = null;
    try {
      reader = new LineNumberReader(new FileReader(new File("F:\\abc.txt")));
      // Read file till the end
      while ((reader.readLine()) != null);
      System.out.println("Count of lines - " + reader.getLineNumber());
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally { 
      if(reader != null){
        try {
          reader.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}

Output

 
Count of lines – 4

That's all for this topic How to Count Lines in a File 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. Java Program to Print Line Numbers With Lines in Java
  2. Reading Delimited File in Java Using Scanner
  3. Reading File in Java Using Files.lines And Files.newBufferedReader
  4. How to Read File From The Last Line in Java
  5. Zipping Files And Folders in Java

You may also like-

  1. How to Create Password Protected Zip File in Java
  2. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  3. Convert double to int in Java
  4. Java Program to Get All The Tables in a DB Schema
  5. Java Abstract Class and Abstract Method
  6. Java Collections Interview Questions And Answers
  7. Java Stream API Tutorial
  8. Interface Static Methods in Java

Monday, June 12, 2023

Invoking Getters And Setters Using Reflection in Java

In the post reflection in java – method it is already explained how you can invoke a method of the class at runtime. In this post we’ll use that knowledge to invoke getters and setters of the class using Java reflection API. In Java you can do it using two ways.

In this post we'll see example of both of these ways to invoke getters and setters of the class.

Using PropertyDescriptor class

A PropertyDescriptor describes one property that a Java Bean exports via a pair of accessor methods. Then using the getReadMethod() and getWriteMethod() you can call the setter and getter for the property.

Invoking getters and setters using PropertyDescriptor example

Here in the example we have a class TestClass which has getter and setter for three fields which are of type int, String and boolean. Then in the GetterAndSetter class there are methods to invoke the getters and setters of the given class.

TestClass.java

package org.prgm;

public class TestClass {
 private int value;
 private String name;
 private boolean flag;
 public int getValue() {
  return value;
 }
 public void setValue(int value) {
  this.value = value;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public boolean isFlag() {
  return flag;
 }
 public void setFlag(boolean flag) {
  this.flag = flag;
 }
}

GetterAndSetter.java

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class GetterAndSetter {
 public static void main(String[] args) {
  GetterAndSetter gs = new GetterAndSetter();
  TestClass tc = new TestClass();
  gs.callSetter(tc, "name", "John");
  gs.callSetter(tc, "value", 12);
  gs.callSetter(tc, "flag", true);
  // Getting fields of the class
  Field[] fields = tc.getClass().getDeclaredFields();
  
  for(Field f : fields){
   String fieldName = f.getName();
   System.out.println("Field Name -- " + fieldName);
  }
  gs.callGetter(tc, "name");
  gs.callGetter(tc, "value");
  gs.callGetter(tc, "flag");
 }
 
 private void callSetter(Object obj, String fieldName, Object value){
  PropertyDescriptor pd;
  try {
   pd = new PropertyDescriptor(fieldName, obj.getClass());
   pd.getWriteMethod().invoke(obj, value);
  } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 private void callGetter(Object obj, String fieldName){
  PropertyDescriptor pd;
  try {
   pd = new PropertyDescriptor(fieldName, obj.getClass());
   System.out.println("" + pd.getReadMethod().invoke(obj));
  } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Output

Field Name -- value
Field Name -- name
Field Name -- flag
John
12
true

Scanning methods of the class and look for set and get methods

Another way to invoke the getters and setters using Java reflection is to scan all the methods of the class through reflection and then find out which are the getters and setters method.

It is particularly useful to use this way to call get methods if you have lots of fields in a class. Calling set method that way won’t be of much help as you will have to still invoke individual method with the value that has to be set.

Logic to identify get method

get method starts with get or is (in case of boolean), it should not have any parameters and it should return a value.

Logic to identify set method

set method starts with set and it should have a parameter and it shouldn't return any value which means it should return void.

In the example same Java bean class as above TestClass is used.

In the GetterAndSetter class there are methods to identify the getters and setters of the given class. If it is a get method that is invoked to get the value. For set method invocation is done to set the property values.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class GetterAndSetter {
  public static void main(String[] args) {
    TestClass tc = new TestClass();
    // get all the methods of the class
    Method[] methods = tc.getClass().getDeclaredMethods();
    // Initially calling all the set methods to set values
    for(Method method : methods){
      if(isSetter(method)){
        System.out.println("Setter -- " + method.getName());
        try {
          if(method.getName().contains("Name")) {
            method.invoke(tc, "John");
          } 
          if(method.getName().contains("Value")) {
            method.invoke(tc, 12);
          }
          if(method.getName().contains("Flag")) {
            method.invoke(tc, true);
          }
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }    
      }
    }
    // calling getters
    for(Method method : methods){
      if(isGetter(method)){
        try {
          Object obj = method.invoke(tc);
          System.out.println("Invoking "+ method.getName() + " Returned Value - " + obj);
        } 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();
        }
      }   
    }
  }

  private static boolean isGetter(Method method){
    // identify get methods
    if((method.getName().startsWith("get") || method.getName().startsWith("is")) 
        && method.getParameterCount() == 0 && !method.getReturnType().equals(void.class)){
      return true;
    }
    return false; 
  }

  private static boolean isSetter(Method method){
    // identify set methods
    if(method.getName().startsWith("set") && method.getParameterCount() == 1 
        && method.getReturnType().equals(void.class)){
      return true;
    }
    return false; 
  }
}

Output

Setter -- setName
Setter -- setValue
Setter -- setFlag
Invoking getName Returned Value - John
Invoking getValue Returned Value - 12
Invoking isFlag Returned Value - true

That's all for this topic Invoking Getters And Setters Using Reflection in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Generating Getters And Setters Using Reflection in Java
  2. Java Reflection API Tutorial
  3. Reflection in Java - Getting Class Information
  4. Reflection in Java - Getting Field Information
  5. Reflection in Java - Getting Constructor Information

You may also like-

  1. How to Sort Elements in Different Order in TreeSet
  2. Java Lambda Expression Callable Example
  3. How to Run a Shell Script From Java Program
  4. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  5. Java Stream API Examples
  6. How to Fix The Target Type of This Expression Must be a Functional Interface Error
  7. PermGen Space Removal in Java 8
  8. Marker Interface in Java