Tuesday, January 31, 2023

JavaScript Array slice() method With Examples

Javascript array slice() method is used to slice a portion of an array which is returned as a new array. Portion that is sliced is selected based on the passed start and end.

slice() method syntax

slice(start, end)

start- Index from where extraction has to be started. Index is zero based. This parameter is optional, if not passed starting index is considered as 0.

end- Index to end the extraction. slice() extracts up to but not including end. This parameter is optional, if not passed extraction ends at the last element of the array.

Return value

A new array containing the extracted elements. Note that returned array is a shallow copy which means any change in the returned array will also reflect in original array.

Note that slice() method also works with negative indexes. Negative index counts back from the end of the array. Last element has the index of -1, second last has the index of -2 and so on. if start < 0, start + array.length is used.

slice() method example

1. Using slice() method with different start and end parameters.

const cities = ['New Delhi', 'Mumbai', 'Chennai', 'Varanasi', 'Bangalore'];

//Without passing start and end
let newCities = cities.slice();
console.log(newCities); //['New Delhi', 'Mumbai', 'Chennai', 'Varanasi', 'Bangalore']

// From index 1 to end
newCities = cities.slice(1);
console.log(newCities); //['Mumbai', 'Chennai', 'Varanasi', 'Bangalore'];

//From index 1 to 3 (3 not included in the result)
newCities = cities.slice(1, 3);
console.log(newCities); //['Mumbai', 'Chennai'];

//From index 0 to -2 
newCities = cities.slice(0, -2);
console.log(newCities); //['New Delhi', 'Mumbai', 'Chennai'];

Using slice() with array of objects

When you use slice() method a shallow copy of a portion of an array is created. Since it is a shallow copy so object references remain same as in original array. Let's try to understand it with an example, suppose you have an array of persons object and you slice it to get a portion of it.

const persons = [{id:1, name:"Ajay", age:9}, 
	 {id:2, name:"Rajiv", age:22}, 
	 {id:3, name:"Bosco", age:25},
	 {id:4, name:"Albert", age:3}];

// Getting object at index 1
let newPersons = persons.slice(1, 2);
console.log(newPersons); //[{id:2, age:22, name:"Rajiv"}]

Now if you try to change object field in this new array it also reflects in the original array because of shared object reference.

newPersons[0].name = "Amit";
console.log(newPersons); // {id: 2, name: 'Amit', age: 22}
console.log(persons);
/* {id: 1, name: 'Ajay', age: 9},
{id: 2, name: 'Amit', age: 22},
{id: 3, name: 'Bosco', age: 25},
{id: 4, name: 'Albert', age: 3}*/

That's all for this topic JavaScript Array slice() method With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Array map() Method
  2. JavaScript filter Method
  3. React Declarative Approach
  4. React Virtual DOM

You may also like-

  1. Abstraction in Java
  2. Lambda expressions in Java 8
  3. Volatile Keyword in Java With Examples
  4. How to Display Pyramid Patterns in Java - Part2
  5. Spring depends-on Attribute and @DependsOn With Examples

Monday, January 30, 2023

JavaScript Array map() Method With Examples

In this tutorial we'll see how to use the JavaScript Array map() method.

Suppose you have a requirement to apply some logic to each element of an array then map() method is a more convenient choice rather than iterating the array and then processing each element.

map() method

With map() you provide a function that is called upon each element of the array and a new array is created with the modified elements.

Syntax of map() method

map(callbackFn, thisArg)

Here parameters are-

  1. callbackFn- A function to execute for each element in the array.
  2. The callback function is called with the following arguments:
    • currentElement- The current array element
    • index- The index of the current element. Optional parameter and you generally won't need this parameter.
    • array- The array map() was called upon. You generally won't need this parameter.
  3. thisArg- A value to use as this when executing callbackFn. This is an Optional parameter.

Callback function can also be written as an arrow function, in that case syntax is

map((element, index, array) => { /* … */ })

or the one you'll use more frequently

map((element) => { /* … */ })

Return value

Method returns a new array which is populated with the elements of the original array after each element is processed by the callback function.

Note that the map() method is an iterative method (iterates through all the elements in the array). This method doesn't change the original array.

Javascript map method examples

1. Using map() to square each element of an array.

const numArr = [3, 5, 6, 9];

const newArr = numArr.map(getSquare);

console.log(newArr); // [9, 25, 36, 81]

function getSquare(num){
	return num * num;
}

Same thing with arrow function

const numArr = [3, 5, 6, 9];
const newArr = numArr.map(n => n * n);
console.log(newArr); // [9, 25, 36, 81]

2. Increase each element by 10%.

const numArr = [300, 500, 600, 100];

const newArr = numArr.map(n => n + (n*10/100));

console.log(newArr); // [330, 550, 660, 110]

3. Using map() with array of objects. In the example there is a persons array containing person object with fields id, firstName, lastName, age, salary. You have to create a new array with objects having fields as name- which merges both first name and last name and salaries are increased by 10%.

const persons = [{id:1, firstName:"Ajay", lastName:"Bisht", age:9, salary: 10000}, 
   {id:2, firstName:"Rajiv", lastName:"Vishnoi", age:22, salary: 12000}, 
   {id:3, firstName:"Bosco", lastName:"Caesar", age:25, salary: 20000},
   {id:4, firstName:"Albert", lastName:"Wadlow", age:3, salary: 30000}];

const newArr = persons.map(p => {
    pObj = {};
    pObj.name = p.firstName + " " + p.lastName;
    pObj.salary = p.salary + (p.salary *10/100);
    return pObj;
  });


console.log(newArr); 

/*
[{name: 'Ajay Bisht', salary: 11000}, 
{name: 'Rajiv Vishnoi', salary: 13200}, 
{name: 'Bosco Caesar', salary: 22000}, 
{name: 'Albert Wadlow', salary: 33000}]*/

That's all for this topic JavaScript Array map() Method With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript filter Method
  2. JavaScript Arrow Function With Examples
  3. JavaScript Import and Export
  4. Controlled and Uncontrolled Components in React

You may also like-

  1. Angular Property Binding With Examples
  2. How to Sort HashSet in Java
  3. Read or List All Files in a Folder in Java
  4. Difference Between Encapsulation And Abstraction in Java
  5. How to Inject Null And Empty String Values in Spring

Sunday, January 29, 2023

Concatenating Lists in Python

In this post we’ll see how to concatenate or join two lists in Python.

1. The best way to join two lists in Python is to use ‘+’ operator.

num_list1 = [1,2,3,4]
num_list2 = [5,6,7]
#concatenating lists using + operator
num_list1 = num_list1 + num_list2
print('Joined List-', num_list1)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7]

2. If you are asked to write a program to join two lists in Python without using any inbuilt function or operator then you can use for loop to iterate one of the list and add elements to another list.

num_list1 = [1,2,3,4]
num_list2 = [5,6,7]
# iterate elements of list
for i in num_list2:
    num_list1.append(i)
print('Joined List-', num_list1)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7]

3. You can also join two lists using list comprehension in Python. Trick here is to create a list of lists and then flatten it.

num_list1 = [1, 2, 3, 4]
num_list2 = [5, 6, 7, 8]
joined_list = [j for s in (num_list1, num_list2) for j in s]
print('Joined List-', joined_list)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7, 8]

4. For joining two lists you can also use list.extend() method where you can pass another list as argument.

num_list1 = [1, 2, 3, 4]
num_list2 = [5, 6, 7, 8]
num_list1.extend(num_list2)
print('Joined List-', num_list1)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7, 8]

5. Using itertools.chain(*iterables) method that make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

This method returns itertools.chain object which is a generator iterator. By passing it to list() type constructor you can get joined list.

import itertools
num_list1 = ['a', 'b', 'c', 'd']
num_list2 = ['e', 'f', 'g', 'h']
joined_list = list(itertools.chain(num_list1, num_list2))

print('Joined List-', joined_list)

Output

Joined List- ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

That's all for this topic Concatenating Lists 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. List in Python With Examples
  2. Named Tuple in Python
  3. Python for Loop With Examples
  4. String Length in Python - len() Function
  5. Keyword Arguments in Python

You may also like-

  1. Magic Methods in Python With Examples
  2. Python Program to Count Occurrences of Each Character in a String
  3. Interface in Python
  4. String Slicing in Python
  5. ArrayList in Java With Examples
  6. final Keyword in Java With Examples
  7. Just In Time Compiler (JIT) in Java
  8. Spring Job Scheduling Using TaskScheduler And @Scheduled Annotation

Friday, January 27, 2023

Find All Permutations of a Given String Java Program

Java program to find all the permutations of a given String can be written using both recursive and non-recursive methods. In this post we'll see both kind of solutions.

Recursive is easy to code but a little difficult to visualize where as non-recursive is a little difficult to code but once you know the logic it is easy to visualize what code is doing.

Java program for finding permutations of a String - Non Recursive

Logic for the non recursive solution is as follows-

  1. First thing to do is to sort the given string in ascending order that is the first permutation so print it.
  2. Now we have to generate all the other permutations until the string is sorted in descending order. That becomes the last permutation to be printed and signals the end of the program.
  3. For every permutation previous permutation becomes the starting point and from there the steps are-
    1. Find the rightmost char in the String which is smaller than the next character.
      For example, if String is BCDA then you need to scan through the chars, B is smaller than the next char 'C' but remember you have to find the rightmost character and 'C' is also smaller than the next character 'D' that means 'C' is the char you are looking for. Let's call this char as 'CHAR1'.
    2. Second step is to find the ceiling of the 'CHAR1' starting from the index of the 'CHAR1'. Ceiling here means starting from the index of the 'CHAR1' you have to find the smallest character which is greater than the 'CHAR1'. Let's call this char as 'CHAR2'.
      As exp. If string is BCDAE and C is 'CHAR1' then you are looking for the smallest character with in the String "DAE" which is greater than C. So it should be D so D is 'CHAR2' in this case.
    3. Swap these 2 characters found using Step1 and Step2 i.e. CHAR1 and CHAR2.
    4. In the resultant string take the substring after the index of 'CHAR1' till end and sort it.

Let's see all the steps with an example- If passed String is 'ABCDEF' and at some point the permutation is 'CFADEB' then in order to find the next permutation.

In Step1 it will go through the following combinations to find the 'CHAR1' CFADEB - C-F, F-A, A-D, D-E, E-B So CHAR1 is D.

In Step2 we have to find the smallest char which is greater than D with in the substring EB. So 'CHAR2' is E.

In Step3 - Swapping these will give the String CFAEDB.

In Step 4 - if we use 0 based index then the original index of 'CHAR1' was 3. In String CFAEDB if we take the sub string after index 3 then DB is the resultant string which has to be sorted.

So the end string is CFAEBD and that is the next permutation.

Note that this logic take cares of the duplicate chars too. If you enter "DDDD" as string it will give you only one String "DDDD" as output.

import java.util.Arrays;

public class PermNR {

  public static void main(String[] args) {     
    permute("ABCDEF");
  }
    
  public static void permute(String str){
    char[] temp = str.toCharArray();
    // Step 1. Sort the string
    Arrays.sort(temp);
    System.out.println("String " + String.valueOf(temp));
    int index = 0;
    int lowest = 0;
    while(true){
      // Step 2. Rightmost char smallest than its neighbour
      for(int i = 0; i < temp.length - 1; i++){
        if(temp[i] < temp[i+1]){
          lowest = i;               
        }
      }
      // index of CHAR1
      index = lowest;
      // Step3. Find the ceiling of the 
      int j = findCeiling(temp, index);
      // Breaking condition at this juncture
      // all permutations are printed
      if(j == index) break;
        
      swap(temp, index, j);
      String a = String.valueOf(temp);
      // Step4. Sort the substring
      char[] b = a.substring(index + 1).toCharArray();
      Arrays.sort(b);
      a = a.substring(0, index + 1) + String.valueOf(b);
      temp = a.toCharArray();
      System.out.println( "String " + String.valueOf(temp));
      //}
    }                        
  }
    
  /**
  * 
  */
  public static int findCeiling(char[] temp, int index){
    int k = index;
    char test = temp[index];
    while (k < temp.length - 1){
      if(temp[index] < temp[k + 1]){
        index = k + 1;
        break;
      }
      k++;
    }
    k = index;
    while (k < temp.length - 1){
      if((temp[index] > temp[k + 1]) && (temp[k + 1] > test)){
        index = k + 1;
      }
      k++;
    }
    return index;
  }
    
  /**
  * Method used for swapping the char
  */
  private static void swap(char[] str, int i, int j){
    char temp = str[i];
    str[i] = str[j];
    str[j] = temp;
  }
}

Permutations of a String - Recursive Java code

Here the method will call itself, keeping portion of a string as constant. A base condition is also needed which is when string length is 0.

public class PermDemo {
  public static void main(String[] args) {
    permutation("abcde");
  }
  public static void permutation(String str) {
    permutation("", str);
  }
  // recursive method
  private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0){
      System.out.println(prefix);
    }
    else {
      for (int i  = 0;  i < n;  i++){
        //System.out.println("prefix " + prefix + " i " + i);
        permutation(prefix + str.charAt(i), str.substring(0, i) 
          + str.substring(i+1, n));
      }
    }
  }
}

Source for recursive code is : http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html

Explanation

After first base point when n becomes 0 we'll have these 3 calls. Note that for all these calls i will be 0 as permutation method is called again.

permutation("a", "bc");
permutation("ab", "c");
permutation("abc", "");

Since method calls follow stack data structure so LIFO (Last In First Out) will be followed. Let's lay out our method calls in that way.

permutation("abc", "");
permutation("ab", "c");
permutation("a", "bc");

Now first call will print the String "abc", second call permutation("ab", "c") will go in the for loop with i = 1 and n = 1 so it will come out and won’t print anything as for loop has condition (i < n). Third call permutation(“a”, “bc”); will go in the for loop with i =1 and n=2. Which will lead to following calls again following that same pattern as explained above it will print acb.

Permutation("a", "bc");
Permutation("ac", "b");
Permutation("acb", "");

That's all for this topic Find All Permutations of a Given String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Check if Given String or Number is a Palindrome Java Program
  2. Java Program to Find First Non-Repeated Character in a Given String
  3. Add Double Quotes to a String Java Program
  4. Count Number of Words in a String Java Program
  5. Print Odd-Even Numbers Using Threads And wait-notify Java Program

You may also like-

  1. Fibonacci Series Program in Java
  2. Find Largest and Second Largest Number in Given Array Java Program
  3. How to Convert Date And Time Between Different Time-Zones in Java
  4. Polymorphism in Java
  5. How ArrayList Works Internally in Java
  6. Race condition in Java multi-threading
  7. Callable and Future in Java With Examples
  8. Autodiscovery of Bean Using component-scan in Spring

Tuesday, January 24, 2023

Spring Constructor Based Dependency Injection

In the post Dependency Injection in Spring I have already talked about dependency injection. In this post we'll explore one of the type of the dependency injection called Constructor based dependency injection in Spring.

Refer Setter-based dependency injection in Spring to know about another variant of dependency injection; Setter injection.

In Constructor based dependency injection, Spring IOC container invokes a class' constructor with arguments that represent the dependencies of that class.


Constructor Dependency Injection Example

Let's see an example of constructor dependency injection in Spring, there is one class called PayServiceImpl which is dependent on Payment class and also has a field amount of type int and those constructor arguments are injected through a constructor DI.

Monday, January 23, 2023

Spring MVC Form Validation Example

In this post we’ll see a Spring MVC form validation example using Bean Validation API.

Technologies used

Following is the list of tools used for the Spring MVC form example with bean validation.

  1. Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  2. Java 10
  3. javax.validation API (2.1.0)
  4. hibernate-validator (6.0.12)
  5. Tomcat server V 9.0.10
  6. Eclipse Photon 4.8.0 for Java EE development (This Eclipse version supports Java 10)

Spring MVC Project structure using Maven

Maven Dependencies

Apart from Spring dependencies following dependencies are also to be added to the pom.xml for Spring bean validation.

<dependency>
  <groupId>javax.validation</groupId>
  <artifactId>validation-api</artifactId>
  <version>2.0.1.Final</version>
</dependency>
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>6.0.12.Final</version>
</dependency>

This should add the following jars-

validation-api-2.0.1.Final.jar
hibernate-validator-6.0.12.Final.jar
jboss-logging-3.3.2.Final.jar
classmate-1.3.4.jar

Why Bean Validation API and Hibernate Validator

Bean Validation API 2.x is based on the JSR 380 specification and HibernateValidator is the certified implementation of Bean Validation API. Using Hibernate Validator you can add application constraints in the form of annotations to your bean class.

Some of the annotations that are defined in Java Bean Validation API are as follows-

  • @NotBlank- The annotated element must not be null and must contain at least onenon-whitespace character.
  • @NotEmpty- The annotated element must not be null nor empty.
  • @NotNull- The annotated element must not be null.
  • @Size- The annotated element size must be between the specified boundaries. Boundaries can be specifies using main and max attributes.
  • @Digits- The annotated element must be a number within accepted range.
  • @Max- The annotated element must be a number whose value must be lower orequal to the specified maximum.
  • @Min- The annotated element must be a number whose value must be higher orequal to the specified minimum.
  • @Email- The string has to be a well-formed email address.

Spring MVC form example with validations step by step

In this Spring MVC user registration form example along with validation for fields the flow of the application is as given below.

  1. First is the home page (home.jsp) having a link to register a user.
  2. Clicking that link opens a form for registering a user (userRegister.jsp) where the fields are bound to the model bean User. We also need to validate the fields bound to the beans.
  3. On submitting the form the validation is done as per configuration and either the show user page (user.jsp) which just displays the entered field or the registration form with errors is displayed based on whether there are errors or not.

home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC tutorial - Home JSP</title>
</head>
<body>
  <div>${message}</div>
  <a href='<s:url value="/registerUser"></s:url>'>Register User</a>
</body>
</html>

This is the landing page, as you can see Spring tags library is used here for creating the URL. For that you need to add the following line in your JSP.

<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>

The request for home page is handled by the following handler method in the Spring controller.

@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHome(Model model) {  
 model.addAttribute("message", "Spring MVC Example - Form Processing");
 return "home";
}

The request path “/registerUser” is handled by the following handler method in the Spring controller.

@RequestMapping(value = "/registerUser", method = RequestMethod.GET)
public String registerUser(Model model) { 
 model.addAttribute(new User());
 return "userRegister";
}

As you can see in this handler method a new User instance is set into the model. It is required for binding a User instance to the Spring form. The logical view name returned by this method is “userRegister” which leads to the opening of registration form.

UserRegister.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Registration</title>
<style>
  .error { 
    color: green; font-weight: bold; 
  }
</style>
</head>
<body>
  <form:form action="showUser" modelAttribute="user" method="post">
    <table>
      <tr>
        <td>
          <form:label path="firstName">First Name</form:label>
        </td>
        <td>
          <form:input path="firstName" id="firstname" />
        </td>
        <td><form:errors path="firstName" cssClass="error"/></td>
      </tr>
      <tr>
      <td>
        <form:label path="lastName">Last Name</form:label>
      </td>
      <td>
        <form:input path="lastName" id="lastname" />
      </td>
        <td><form:errors path="lastName" cssClass="error"/></td>
      </tr>
      <tr>
        <td>
          <form:label path="passWord">Password</form:label>           
        </td>
        <td>
          <form:password path="passWord" id="password" />
        </td>
        <td><form:errors path="passWord" cssClass="error"/></td>
      </tr>
      <tr>
      <td>
        <form:label path="email">Email</form:label>
      </td>
      <td>
        <form:input path="email" id="email" />                 
      </td>
        <td><form:errors path="email" cssClass="error"/></td>
      </tr>
      <tr>
        <td>Subscribe to newsletter?:</td>
        <td><form:checkbox path="receiveNewsletter"/></td>
      </tr>
      <tr>
        <td><input type="submit" value="Submit"></td>
      </tr>
    </table>
  </form:form>
</body>
</html>

In this JSP (which is the user registration form), Spring form tags are used for Spring MVC form fields. The tag of interest here is “errors”. This tag renders field errors in an HTML 'span' tag. It provides access to the errors created in your controller or those that were created by any validators associated with your controller.

Also notice the attribute modelAttribute="user" in the form tag. This binds the form to the named variable. By default JSP assumes that the variable name of the form backing object is 'command' but it is a good practice to give your own name along with the modelAttribute.

The submission of this form is handled by the following handler method.

@RequestMapping(value = "/showUser", method = RequestMethod.POST)
public String showUser(@Valid @ModelAttribute("user") User user, BindingResult result, Model model) { 
 if(result.hasErrors()) {
  return "userRegister";
 }
 model.addAttribute("User", user);
 return "user";
}
If you notice the method parameter @Valid @ModelAttribute("user") User user, @ModelAttribute used here gives the same “user” instance as bound to Spring form. @Valid provides support for declarative validation of the bean annotated with @Valid annotation.

BindingResult stores the result of the Spring form validation and contains errors that may have occurred. That’s what is used for finding out if there are any errors in the Spring form validation, if there are errors then the same form is displayed again with errors. Relevant errors are displayed using the errors tag in the JSP. If there are no errors then the entered fields are displayed in the JSP page user.jsp.

user.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC tutorial - User</title>
</head>
<body>
  <table>
    <tr>
      <td>First Name: ${User.firstName}</td>
    </tr>
    <tr>
      <td>Last Name: ${User.lastName}</td>
    </tr>
    <tr>
      <td>Email: ${User.email}</td>
    </tr>
    <tr>
      <td>Requires Newsletter: ${User.receiveNewsletter}</td>
    </tr>
  </table>
</body>
</html>

Spring bean validation using annotations

Till now we have seen the configuration and code required for Spring MVC form and bean validation code required for the view and controller. Not let’s shift focus to the Model.

Model bean (User.java)

import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class User {
 @NotNull
 @Size(min=5, max=15, message="{firstName.size}")
 private String firstName;
 @NotNull
 @Size(min=5, max=15, message="{lastName.size}")
 private String lastName;
 @NotNull
 @Size(min=8, max=20, message="{passWord.size}")
 private String passWord;
 @NotNull
 @Email(message="{email.msg}")
 private String email;
 
 private boolean receiveNewsletter;
    
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getPassWord() {
  return passWord;
 }
 public void setPassWord(String passWord) {
  this.passWord = passWord;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 public boolean isReceiveNewsletter() {
  return receiveNewsletter;
 }
 public void setReceiveNewsletter(boolean receiveNewsletter) {
  this.receiveNewsletter = receiveNewsletter;
 }
}

This is the bean where Spring bean validation is configured for the form. Spring framework supports the Java Validation API in Spring MVC. Fields are annotated with the javax.validation.constraints annotation, for example firstName field is annotated with @NotNull which means this field can not be null and with @Size with max and min attribute for setting the minimum and maximum allowed characters. Using message attribute you can set the message which is referred from a properties file.

Properties file for validation messages

By default Spring framework looks for a file named ValidationMessages.properties, if you are using properties file with another name then some configuration is required. For this Spring form example we’ll name the properties files as “messages.properties” and see what all configuration is required to make it work.

messages.properties

firstName.size=First name is required and should be between {min} and {max} characters.
lastName.size=Last name is required and should be between {min} and {max} characters.
passWord.size=Password is required and should be between {min} and {max} characters.
email.msg=Please enter a valid email in the format abc@xyz.com.

Ensure that the key for each message is same as the placeholder you have given in the message attribute in your model bean.

Configuration for Spring bean validation

Following configuration is required in your Servlet’s XML file.

<mvc:annotation-driven validator="validator"/>

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/messages"/>
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="validationMessageSource" ref="messageSource"/>
</bean> 

In the class ReloadableResourceBundleMessageSource you need to set path for your properties file as basename. Since I stored messages.properties file at the location /WEB-INF/messages.properties thus the value "/WEB-INF/messages".

Using LocalValidatorFactoryBean you can configure a default JSR-303 Validator as a Spring bean. Ensure that a JSR-303 provider, such as Hibernate Validator, is present in the classpath, that implementation will be detected automatically.

Also need to provide the bean name of the Validator that is to be used to validate Controller model objects using the validator attribute in <mvc:annotation-driven /> tag.

Spring MVC Form Example With Bean Validation - Controller class

We have already seen the relevant handler methods along with the JSPs, here is the full controller class used for the Spring form example with bean validation.

MessageController.java

import javax.validation.Valid;
import org.netjs.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MessageController {
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String showHome(Model model) {  
  model.addAttribute("message", "Spring MVC Example - Form Processing");
  return "home";
 }
 
 @RequestMapping(value = "/registerUser", method = RequestMethod.GET)
 public String registerUser(Model model) { 
  model.addAttribute(new User());
  return "userRegister";
 }
 
 @RequestMapping(value = "/showUser", method = RequestMethod.POST)
 public String showUser(@Valid @ModelAttribute("user") User user, BindingResult result, Model model) { 
  if(result.hasErrors()) {
   return "userRegister";
  }
  model.addAttribute("User", user);
  return "user";
 }
}

Home page

Registration form errors

Registration form success

That's all for this topic Spring MVC Form Validation 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 Web MVC Tutorial
  2. Spring MVC Example With @RequestParam Annotation
  3. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  4. Spring MVC File Upload (Multipart Request) Example
  5. How to Read Properties File in Spring Framework

You may also like-

  1. Using Spring Profiles to Switch Environment
  2. Run Time Injection Using Spring Expression Language(SpEL)
  3. Difference Between component-scan And annotation-config in Spring
  4. Different Bean Scopes in Spring
  5. ConcurrentHashMap in Java
  6. Race Condition in Java Multi-Threading
  7. Type Casting in Java
  8. How to Create Password Protected Zip File in Java

Sunday, January 22, 2023

Spring Java Configuration Example Using @Configuration

In this post we'll see Spring Java based configuration example using @Configuration annotation. For creating project structure Maven is used.

Technologies used

  • Spring 5.0.4
  • JDK 1.8
  • Apache Maven 3.3.3
  • Eclipse Luna 4.2.2

Spring Java Config example step by step

Let's go step by step to see how these classes are configured using Java configuration.

  1. Provide dependencies in pom.xml of Maven

    <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.exp</groupId>
      <artifactId>Spring-Example</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>Spring-Example</name>
      <url>http://maven.apache.org</url>
      <properties>
        <java.version>1.8</java.version>
        <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>         
      </dependencies>
    </project>
    

    Note that you'll already have most of the entries in pom.xml, you just need to add dependencies for spring-core and spring-context and an entry for spring.version in properties element. spring-context is needed for the annotations.

  2. Spring JavaConfig example - Bean classes

    In the example we have 2 classes PaymentService and CashPayment. PaymentService class needs an instance of CashPayment (dependency). Since Spring promotes loose coupling so it is always recommended to code to interfaces. So we'll also create interfaces for the classes.

    Payment Service

    public interface IPayService {
        void performPayment();
    }
    
    public class PayServiceImpl implements IPayService {
     private IPayment payment;
     
     public void performPayment() {
      payment.executePayment();
     }
     
     public IPayment getPayment() {
      return payment;
     }
    
     public void setPayment(IPayment payment) {
      this.payment = payment;
     }
    }
    

    PayServiceImpl class has a dependency on instance of type IPayment, this dependency is defined in the Configuration class i.e. class that is annotated with @Configuration annotation.

    Cash Payment

    public interface IPayment {
     void executePayment();
    }
    
    public class CashPayment implements IPayment{
     public void executePayment() {
      System.out.println("Perform Cash Payment "); 
     }
    }
    
  3. Spring JavaConfig example - JavaConfig class

    For Java based configuration in Spring you need to annotate JavaConfig class with @Configuration annotation. When a class is annotated with @Configuration annotation the annotated class is identified as a configuration class. This configuration class will contain the @Bean annotated methods, these methods will provide details about the beans that are to be created and managed by the Spring application context.

    It's better to keep config classes in a separate package so create a new package and create the config class (I have named it AppConfig.java) there.

    package org.netjs.exp.config;
    
    import org.netjs.exp.Spring_Example.CashPayment;
    import org.netjs.exp.Spring_Example.IPayService;
    import org.netjs.exp.Spring_Example.IPayment;
    import org.netjs.exp.Spring_Example.PayServiceImpl;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class AppConfig {
     @Bean
     public IPayService payService(){
      PayServiceImpl payServiceImpl = new PayServiceImpl();
      //setting bean dependency
      payServiceImpl.setPayment(cashPayment());
      return payServiceImpl;
     }
     
     @Bean
     public IPayment cashPayment(){
      return new CashPayment(); 
     }
    }
    

    Here it can be seen how the methods that create the beans are annotated with @Bean annotation. Also note that in this configuration class I have given example of setter based dependency injection.

  4. Java class to run the application

    package org.netjs.exp.Spring_Example;
    
    import org.netjs.exp.config.AppConfig;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    import org.springframework.context.support.AbstractApplicationContext;
    
    public class App 
    {
      public static void main( String[] args ){
        AbstractApplicationContext context = new AnnotationConfigApplicationContext
         (AppConfig.class);
        IPayService bean = (IPayService) context.getBean("payService");
        bean.performPayment();
        context.close();
      }
    }
    

    Output

    May 20, 2018 11:24:27 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@46fbb2c1: startup date [Sun May 20 11:24:27 IST 2018]; root of context hierarchy
    Perform Cash Payment 
    May 20, 2018 11:24:29 AM org.springframework.context.support.AbstractApplicationContext doClose
    INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@46fbb2c1: startup date [Sun May 20 11:24:27 IST 2018]; root of context hierarchy
    

    Here note that AnnotationConfigApplicationContext is used to create the Spring application context. JavaConfig class is passed as parameter to the class constructor. While setting up application context it searches for all the beans in the configuration class by looking for the methods annotated with @Bean annotation.

    Another thing to note here is that by default the bean's id is the same as the name given to the method annotated with @Bean. That's why you can get the PayService bean using-

    context.getBean("payService");
    
    Because in the JavaConfig class method's name is payService. If you want to provide another name then you can use the name attribute. As example if you want to call the payService bean as myPayService then it can be done this way-
    @Bean(name="myPayService")
    public IPayService payService(){
     PayServiceImpl payServiceImpl = new PayServiceImpl();
     payServiceImpl.setPayment(cashPayment());
     return payServiceImpl;
    }
    
    And then it should be called as
     
    IPayService bean = (IPayService) context.getBean("myPayService");
    

Spring Java Configuration example with constructor dependency injection

As I mentioned above, the configuration done was for setter. If you want to use constructor dependency injection then you need to change it a little.

Suppose the PayService class is like this-
 
public class PayServiceImpl implements IPayService {
 
 private IPayment payment;
 public PayServiceImpl(IPayment payment){
  this.payment = payment;
 }
 
 public void performPayment() {
  payment.executePayment();
 }

}
Then in JavaConfig class we have to provide a constructor injection.
package org.netjs.exp.config;

import org.netjs.exp.Spring_Example.CashPayment;
import org.netjs.exp.Spring_Example.IPayService;
import org.netjs.exp.Spring_Example.IPayment;
import org.netjs.exp.Spring_Example.PayServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
 @Bean
 public IPayService payService(){
  return new PayServiceImpl(cashPayment());
 }
 
 @Bean
 public IPayment cashPayment(){
  return new CashPayment(); 
 }
}

That's all for this topic Spring Java Configuration Example Using @Configuration. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring XML Configuration Example
  2. Spring Component Scan Example
  3. Dependency Injection in Spring Framework
  4. @Conditional Annotation in Spring
  5. Spring JdbcTemplate Insert, Update And Delete Example

You may also like-

  1. Dependency Injection Using factory-method in Spring
  2. Bean Definition Inheritance in Spring
  3. Data access in Spring framework
  4. Creating a Maven project in Eclipse
  5. Java ReentrantReadWriteLock With Examples
  6. ConcurrentHashMap in Java With Examples
  7. Deadlock in Java Multi-Threading
  8. Marker Interface in Java

Saturday, January 21, 2023

Spring Setter Based Dependency Injection

In the post Dependency Injection in Spring I have already talked about dependency injection. Dependency Injection exists in two variants.

  • Constructor based Dependency Injection
  • Setter based Dependency Injection

In this post we'll explore one of the type of the dependency injection called Setter based Dependency Injection in Spring.

Refer Spring Constructor Based Dependency Injection to know more about constructor dependency injection in Spring.

In setter based dependency injection, Spring IOC container will call setter methods on your beans after invoking a no-arg constructor or no-arg static factory method to instantiate your bean.

The <property> sub-element of <bean> is used for setter dependency injection. If you need to inject an object dependency use ref element, for primitive and String values use value element.

Spring setter based Dependency Injection Example

Let's see an example to understand it better. There is a PayServiceImpl class which uses Payment Class object to process payment, it has two fields one for Payment class object and another is amount which is an integer field.

In the PayServiceImpl class, there are two fields for which values are set using setter methods. Setter dependency injection is used to inject those values.

 
public interface IPayService {
 void performPayment();
}
 
public class PayServiceImpl implements IPayService {
 private IPayment payment;
 private int amount;
 
 public void performPayment() {
  payment.executePayment(amount);
 }
 
 public IPayment getPayment() {
  return payment;
 }
 public void setPayment(IPayment payment) {
  this.payment = payment;
 }

 public int getAmount() {
  return amount;
 }
 public void setAmount(int amount) {
  this.amount = amount;
 }
}

Code for CashPayment class

 
public interface IPayment {
 void executePayment(int amount);
}
 
public class CashPayment implements IPayment{
 public void executePayment(int amount) {
  System.out.println("Perform Cash Payment - " + amount); 
 }
}

XML Configuration file (XML file name - appcontext.xml)

 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
 
  <!-- defining CashPayment bean -->
  <bean id="cashPaymentBean" class="org.netjs.prog.maven_spring.CashPayment" />
 
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="paymentBean" class="org.netjs.prog.maven_spring.PayServiceImpl">
      <property name="payment" ref="cashPaymentBean" />
      <property name="amount" value="100" />
  </bean>
  
</beans>

Here you can see that the properties defined in the PayServiceImpl class are used in the name attribute of the property element. Note that same name as given in the class should be used in the configuration file.

To run this you can use the class App-

public class App {
  public static void main( String[] args ){   
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
     ("appcontext.xml");
    IPayService bean = (IPayService) context.getBean("paymentBean");
    bean.performPayment();
    context.close();
  }
}

Note that it is always recommended to use interfaces rather than concrete classes, more so with Spring as whole idea of dependency injection is to have loose coupling and interfaces help in achieving that.

That's all for this topic Spring Setter Based Dependency Injection. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Expression Language (SpEL) With Examples
  2. Spring depends-on Attribute and @DependsOn With Examples
  3. Spring XML Configuration Example
  4. Wiring Collections in Spring
  5. Dependency Injection Using factory-method in Spring

You may also like-

  1. Autowiring in Spring Using @Autowired and @Inject Annotations
  2. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation
  3. Using Conditional Annotation in Spring Framework
  4. Spring Bean Life Cycle
  5. String in Java Tutorial
  6. LinkedHashSet in Java With Examples
  7. Lambda Expression Examples in Java
  8. Java ReentrantLock With Examples

Friday, January 20, 2023

Ternary Operator in Java With Examples

Java includes a conditional operator known as ternary operator (?:), which can be thought of as a shorthand for an if-else statement. This operator is known as the ternary operator because it uses three operands.

General form of ternary operator in Java

boolean-exp ? expression2 : expression3

If boolean expression evaluates to true then expression2 is evaluated and its value becomes the result of the operator; otherwise (if boolean expression is false) expression3 is evaluated and its value becomes the result of the operator.

For example if you have this statement-

int result = someCondition ? value1 : value2;

The statement should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

Note that in Java Ternary operator both expression2 and expression3 should return the value of same (or compatible) type.

Usage of Java ternary operator

Though switch-case statement in Java provides performance improvement over if-else statement there is no performance improvement if ternary operator is used over an if-else statement but it makes the code more readable and terse.

Ternary operator example-

int val = (i > 10) ? i * 5 : i * 10;

Here val is assigned the value (i * 5) if i is greater than 10 otherwise val is assigned the value (i * 10).

Writing the same thing using if-else will be a multiple line affair.

 
if(i > 10){
  val = i * 5;
}else{
  val = i * 10;
}

If you were to write a method where value is returned using the same logic, with ternary operator the method will look like-

 
public int getValue(int i){
 return (i > 10) ? i * 5 : i * 10;
}

In this case if-else statement can also be made more compact-

 
public static int getValue(int i){
  if(i > 10)
    return i * 5;
  return i * 10;
}

Not its up to you to decide what looks more readable. I feel once you get a grip over ternary operator it will always be more readable.

Another example– This Java ternary operator example uses String expression and prints a message based on the value of the string.

 
String day = "saturday";
System.out.println(((day.equalsIgnoreCase("saturday") || day.equalsIgnoreCase("sunday"))
    ? "weekend! time to party!" : "Working day"));

Output

weekend! time to party!

Nested ternary operator

Ternary operator in Java can be nested but doing that considerably decreases the readability.

As example if you have the logic that number of transactions in a week is-

upto 5 means ok, 
more than 5 and less than 10 means notify the user 
more than 10 means alarm!!

Then you can use the nested ternary operator

String noOfTransactions = (i < 5) ? "ok" : (i > 5 && i < 10) ? "notify" : "alarm";

Generally it is not advisable to use nested ternary operator as it defeats the purpose of making the code more readable in contrast it makes it look more complex and confusing in most of the cases.

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

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Switch-Case Statement in Java With Examples
  2. instanceof Operator in Java With Examples
  3. Arithmetic And Unary Operators in Java
  4. String in Java Tutorial
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Java Pass by Value or Pass by Reference
  2. Inheritance in Java
  3. Abstraction in Java
  4. Difference between Encapsulation and Abstraction in Java
  5. Initializer block in Java
  6. HashMap Vs LinkedHashMap Vs TreeMap in Java
  7. Difference Between ArrayList And LinkedList in Java
  8. Difference Between CountDownLatch And CyclicBarrier in Java
  9. Lambda Expressions in Java 8

Thursday, January 19, 2023

List in Python With Examples

List in Python is one of the sequence data type that can store a group of elements. Some of the important points about Python list are-

  1. A list can store elements of different types.
  2. List maintains the insertion order. Elements are inserted sequentially and you can iterate them in the same order.
  3. One of the major difference between list and other data types like string and tuple is that list is mutable. So, it is possible to change content of a list.
  4. Lists can be indexed (both positive and negative) and sliced.

In this article we’ll see some of the features of the Python list, methods of the list and functions that can be used with List with examples.


Creating a list in Python

In Python list is created by grouping elements with in square brackets [], where the elements are separated by comma.

1. A list of integers.

numbers = [1, 3, 5, 7]
print(numbers) # [1, 3, 5, 7]

2. Creating empty list in Python.

alist = []
print(alist) # []

3. List with element of different types.

alist = [12, 'Sheldon', 'M', 9.99, 9.98]
print(alist)
print(type(alist[0]))
print(type(alist[1]))
print(type(alist[3]))

Output

[12, 'Sheldon', 'M', 9.99, 9.98]
<class 'int'>
<class 'str'>
<class 'float'>

As you can see type of the element at the 0th index is int, type of the element at the 1st index is str where as type of the element at the 3rd index is float.

4. Creating list using type constructor- list()

By passing an iterable in the type constructor list() you can create a list. If no argument is given, the constructor creates a new empty list, [].

alist = list((1,2,3,4))
print(alist) #[1, 2, 3, 4]
alist = list('abcd')
print(alist) #['a', 'b', 'c', 'd']
alist = list(range(1, 9, 2))
print(alist) #[1, 3, 5, 7]

5. Creating a nested list.

You can create a list with in another list (nested list) by grouping elements enclosed in a square bracket with in a square bracket.

alist = [1, 2, [3, 4], 5, 6]
print(alist) #[1, 2, [3, 4], 5, 6]

Refer this post List Comprehension in Python With Examples to see an elegant way to create a list using list comprehension.

Accessing Python List elements using index

List in python uses index starting from 0 to (list_length-1), it also uses negative indexing which starts at -1 from the end (right most element) and goes till list_length.

Here is an example showing list indexing for the stored elements.

Python List index

To access an element you can pass the index in the square brackets. For example to access the 5th element in a list you will pass list[4], as index starts from 0.

alist = [2, 3, 6, 7, 9]
#1st element
print(alist[0])
#last element
print(alist[4])
#last element
print(alist[-1])
#first element
print(alist[-5])

Output

2
9
9
2

Trying to pass index beyond the index range of the list results in ‘index error’. For example here is a list having 5 elements so index range for the list is 0..4, trying to access index 5 results in an error.

alist = [2, 3, 6, 7, 9]
print(alist[5])

Output

    print(alist[5])
IndexError: list index out of range

Slicing a list in Python

Just like string slicing in Python you can do list slicing too which returns a new list.

Format of List slicing is as follows-

Listname[start_position: end_position: increment_step]
  • start_position is the index from which the slicing starts, start_position is included.
  • end_position is the index at which the list slicing ends, end_position is excluded.
  • increment_step indicates the step size. For example if step is given as 2 then every alternate element from start_position is accessed.

All of these parameters are optional, if start_position is not specified then the slicing starts from index 0. If end_position is not specified then the slicing ends at list_length – 1 (last index). If increment_step is not specified then increment step is 1 by default.

alist = [2, 4, 6, 8, 10]
print(alist[1:len(alist):2]) #[4, 8]

In the example start_position is 1, end_position is 5 and increment_step is 2 thus the elements at indices 1 and 3 are sliced to create another list.

alist = [2, 4, 6, 8, 10]
print(alist[::])#[2, 4, 6, 8, 10]
print(alist[-3:])#[6, 8, 10]

Iterating all elements of a list using for or while loop

1. Using for loop

alist = [2, 4, 6, 8, 10]
for i in alist:
  print(i)

Output

2
4
6
8
10

As you can see from the output insertion order is maintained in the list.

2. Using while loop

alist = [2, 4, 6, 8, 10]
i = 0;
while i < len(alist):
  print(alist[i])
  i += 1

Output

2
4
6
8
10

Adding elements to a list

To add elements to a list you can use one of the following methods-

  • list.append(x)- Add an item to the end of the list.
  • list.insert(i, x)- Insert an item at a given position. The first argument is the index of the element before which to insert.
  • list.extend(iterable)- Extend the list by appending all the items from the iterable.
alist = [2, 4, 6, 8, 10]
# add new element at the end
alist.append(12)
print(alist)
# insert element before index 4
alist.insert(4, 9)
print(alist)
# append elements from another list
alist.extend([14, 16])
print(alist)

Output

[2, 4, 6, 8, 10, 12]
[2, 4, 6, 8, 9, 10, 12]
[2, 4, 6, 8, 9, 10, 12, 14, 16]

Updating elements of a list in Python

Since Python list is mutable so value of the elements in the list can be modified or elements can be deleted.

To update element’s value you need to access that element using indexing or slicing and assign a new value.

alist = [2, 4, 6, 8, 10]
#Updating value of the element at 3rd index
alist[3] = 9
print(alist) #[2, 4, 6, 9, 10]

Using slicing

alist = [2, 4, 6, 8, 10]
#Updating element at 0th and 1st index
alist[0:2] = 1, 2
print(alist) #[1, 2, 6, 8, 10]

Removing element from a Python list

You can remove element from a list using one of the following method.

  • list.remove(x)- Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
  • list.pop([i])- Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. If index is out of range then IndexError is raised.

Python list remove() method example

alist = ['h', 'e', 'l', 'l', 'o']
if 'e' in alist:
  alist.remove('e')
print(alist)

Output

['h', 'l', 'l', 'o']

In the example using membership operator ‘in’ first it is checked whether the element exists in the lists or not, if it does then it is removed using remove() method.

Python list pop() method example

alist = ['h', 'e', 'l', 'l', 'o']
elem = alist.pop(2)
print(elem)

Output

l

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

>>>Return to Python Tutorial Page


Related Topics

  1. Concatenating Lists in Python
  2. Tuple in Python With Examples
  3. Named Tuple in Python
  4. Python while Loop With Examples
  5. Python Generator, Generator Expression, Yield Statement

You may also like-

  1. Python Conditional Statement - if, elif, else Statements
  2. Operator Overloading in Python
  3. Python Program to Check if Strings Anagram or Not
  4. raise Statement in Python Exception Handling
  5. Java Collections Interview Questions And Answers
  6. Volatile Keyword in Java With Examples
  7. Difference Between throw And throws in Java
  8. Quick Sort Program in Java

Wednesday, January 18, 2023

HashMap Vs LinkedHashMap Vs TreeMap in Java

Though HashMap, LinkedHashMap and TreeMap all are implementations of the Map interface and share some traits like

But there are certain differences too related to how elements are ordered, performance etc. So it is very important to know these differences among HashMap, LinkedHashMap and TreeMap in Java as it will help you to make an informed choice about which Map implementation should be used to meet the requirement.

Differences among HashMap, LinkedHashMap and TreeMap in Java

  1. First and most important difference is related to Ordering of the elements.
    HashMap makes no guarantees as to the order of the map.
    LinkedHashMap maintains the insertion order or access order (based on the constructor) of the elements. Which means if we iterate a LinkedHashMap we'll get the keys in the order in which they were inserted in the Map or the order in which its entries were last accessed, from least-recently accessed to most-recently.
    TreeMap stores objects in sorted order. The elements in TreeMap are ordered according to the natural ordering of its keys or a Comparator can be provided at map creation time to provide custom ordering of its keys.

  2. Another difference is related to allowing null as key or value.
    HashMap as well as LinkedHashMap allows one null as key, multiple values may be null though.
    TreeMap does not allow null as key. Any attempt to add null in a TreeMap will result in a NullPointerException. Values may be null.

  3. For HashMap and LinkedHashMap comparison of the elements is done using equals() method.
    As Example in get method for the passed key k, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null.
    TreeMap does the comparison of the keys using the compareTo (or compare) method, depending on whether sorting is done using Comparable or Comparator.
    As Example in get method for the passed key k, if this map contains a mapping from a key k to a value v such that key compares equal to k according to the map's ordering, then this method returns v; otherwise it returns null.

  4. HashMap class extends AbstractMap and implements Map interface.
    LinkedHashMap class extends HashMap and implements Map interface.
    TreeMap class extends AbstractMap and implements NavigableMap interface.

  5. HashMap stores elements in a bucket which actually is an index of the array which means the backing data structure for the HashMap is an array where bucket0 means index[0], bucket1 means index[1] of that array.
    LinkedHashMap extends HashMap and uses the same internal implementation as HashMap. Apart from that it also maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering.
    TreeMap is a Red-Black tree based NavigableMap implementation.

  6. Performance wise HashMap provides constant time performance O(1) for get() and put() method but that is in the ideal case when the Hash function distributes the objects evenly among the buckets. In worst case when equals() and HashCode() implementation is not good it may even become O(n).
    LinkedHashMap also provides constant time performance O(1) for get() and put() method but in general a little slower than the HashMap as it has to maintain a doubly linked list.
    TreeMap provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

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


Related Topics

  1. Difference Between HashMap And Hashtable in Java
  2. How to Loop Through a Map in Java
  3. LinkedHashMap in Java With Examples
  4. HashSet Vs LinkedHashSet Vs TreeSet in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. How to Sort Elements in Different Order in TreeSet
  2. How to Sort ArrayList of Custom Objects in Java
  3. Deadlock in Java Multi-Threading
  4. Difference Between sleep And wait in Java Multi-Threading
  5. How to Fix The Target Type of This Expression Must be a Functional Interface Error
  6. Java Pass by Value or Pass by Reference
  7. Serialization Proxy Pattern in Java
  8. Creating Custom Exception Class in Java

Tuesday, January 17, 2023

Difference Between equals() Method And equality Operator == in Java

Difference between equals() method and equality operator “==” in Java is a frequently asked Java interview question. At the same time it may be a bit confusing for the first-time Java programmer to get the subtle differences between equals and “==”.

So in this post let’s try to find the exact differences between the equals() method and equality operator “==” in Java and where does it make sense to use what.

Java equality operator “==”

equality operator “==” in Java can be used to compare primitive values as well as objects. Though it works just fine with primitive values but in case of objects “==” will compare the references of the objects not the content of the objects.

equals() method in Java

If you want to compare the actual contents of the objects then you will have to override equals method, which is present in Object class so available to all the other classes. Default implementation of equals() in the Object class compares using == operator, so default implementation will compare references.

You will have to override equals method in order to compare your custom class objects.

Difference between equals and “==” in Java

Based on what we have seen so far we can surely list some difference between equals and equality operator “==”.

  1. “==” is an operator where as equals is a method.
  2. “==” can be used with primitive values as well as with objects. Equals method can only be used with objects.
  3. When “==” is used for comparing objects it will compare their references not the actual content. Equals method can compare the actual content of the object but you will have to provide your own implementation for determining the equality of two objects.

Java example using “==” operator and equals()

Let’s move on to see some hands-on code to test the theory stated so far.

public class EqualsMethodDemo {

 public static void main(String[] args) {
    String str1 = new String("Test");
    String str2 = new String("Test");
    
    System.out.println(str1 + " == " + str2 + " - " + (str1 == str2));
    
    System.out.println(str1 + ".equals(" + str2 + ") - " + str1.equals(str2));
 }
}

Output

Test == Test - false
Test.equals(Test) - true

Here two string objects, having the same content, are created. Now comparison of these two strings is done using equality “==” operator and .equals() method.

It can be seen that “==” returns false even though the content of both the string is same. That is because references of both the strings are different. Where as comparison using .equals() returns true.

Here note that String class as well as wrapper classes like Integer, Long provide implementation of equals method which compares the content. Same way for your own classes you will have to provide your own implementation of equals method.

Integer class equals method example

As mentioned above Integer class provides implementation of equals method so that too will compare the content when equal method is used.

public class EqualsMethodDemo {

 public static void main(String[] args) {
  Integer num1 = new Integer(7);
  
  Integer num2 = new Integer(7);
  
  System.out.println(num1 + " == " + num2 + " - " + (num1 == num2));
  
  System.out.println(num1 + " == " + num2 + " - " + num1.equals(num2));
 }
}

Output

7 == 7 - false
7 == 7 - true

That's all for this topic Difference Between equals() Method And equality Operator == 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. Equality and Relational Operators in Java
  2. Conditional Operators in Java With Examples
  3. Ternary Operator in Java With Examples
  4. String Comparison in Java equals(), compareTo(), startsWith() Methods
  5. equals() And hashCode() Methods in Java

You may also like-

  1. Java Pass by Value or Pass by Reference
  2. Access Modifiers in Java - Public, Private, Protected and Default
  3. How HashMap Works Internally in Java
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. Nested Try Statements in Java Exception Handling
  6. Marker Interface in Java
  7. Java Multithreading Interview Questions And Answers
  8. Lambda Expressions in Java 8