Thursday, March 16, 2023

Comparing Enum to String in Java

Sometimes you may have the scenario where you want to compare String to enum type in Java. For example you may have an enum with product codes and you want to check that the passed produce code is one of the predefined product codes or not.

Here one thing to note is directly comparing enum value with a string won't work as they both will be of different types.

For example, notice in the code snippet given below where enum type d is directly compared with the String, it won't give any output as they will never be equal.

Wednesday, March 15, 2023

Shallow Copy And Deep Copy in Java Object Cloning

In this post we’ll see what are shallow copy and deep copy in Java with respect to Java object cloning and what are the differences between shallow copy and deep copy in Java.

Object cloning in Java

Object cloning is the process of creating an exact copy of the existing object. When you clone an object you get a new instance with the same content for the fields in the new object as in existing object.

Object cloning in Java is done using clone() method which is defined in java.lang.Object class. Only those object that implement Cloneable interface are eligible for cloning.

Both shallow copy and deep copy relates to how object is cloned. When object cloning is done using the default clone method (by calling the clone method of the Object class) it returns a shallow copy of the object.

For creating a deep copy of an object you would need to override the clone method.


Shallow copy in Java

As already stated when you use default clone() method, shallow copy of the object is created. What it means is that there would be field-to-field assignment. New object will also have the same fields as the original object and the same content for the fields too. It works fine for primitive data types but in case there is another object reference in your class it may be a problem.

If a class whose object is cloned contains another object then field-to-field assignment will be done for the contained object too in the cloning process. Since Java is pass by value, so copying the value of the object means object reference would be copied and there lies the problem.

Reference of the contained object is shared between the original object and the cloned object and making any change to that object in the cloned object would be reflected in the original object too and vice versa is also true.

For example suppose there is a class ClassB which has another object objA of Class A.
public class ClassB implements Cloneable{
  private ClassA objA;
  ...
  ...
}

When object of ClassB is cloned, objA reference is shared between the original object and the cloned object.

Shallow copy in Java
Shallow copy

Shallow copy Java example

Here we have a Class called ClassA with 2 int fields. Another class ClassB which has a ClassA object and an int field.

Then you create an object objB of ClassB and clone it to get a new object objB2. In both of these objects, reference of ClassA object will be shared.

ClassA

public class ClassA implements Cloneable{
 private int i;
 private int j;
 // Constructor
 public ClassA(int i, int j){
  this.i = i;
  this.j = j;
 }
 public void setI(int i) {
  this.i = i;
 }
 public void setJ(int j) {
  this.j = j;
 }
 public int getI() {
  return i;
 }
 public int getJ() {
  return j;
 }
}

ClassB

public class ClassB implements Cloneable{
 private int x;
 private ClassA objA;
 
 public ClassB(int x, ClassA objA){
  this.x = x;
  this.objA = objA;
 }
 public Object clone() throws CloneNotSupportedException{
  return super.clone();
 }
 public int getX() {
  return x;
 }
 public ClassA getObjA() {
  return objA;
 }
 public void setX(int x) {
  this.x = x;
 }
 public void setObjA(ClassA objA) {
  this.objA = objA;
 }
}

CloningDemo class

public class CloningDemo {

 public static void main(String[] args) {
  ClassB objB = new ClassB(10, new ClassA(20, 30));
  
  ClassB objB2 = null;
  try {
   objB2 = (ClassB)objB.clone();
   
  } catch (CloneNotSupportedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  // value of field i of objA changed 
  // in cloned object
  objB2.getObjA().setI(100); 
  // Value of primitive field x changed 
  // in cloned object
  objB2.setX(1);
  System.out.println("objB.x- " +  objB.getX() + " objB.objA.i- " + objB.getObjA().getI() + " objB.objA.j- " + objB.getObjA().getJ());

  System.out.println("objB2.x- " +  objB2.getX() + " objB2.objA.i- " + objB2.getObjA().getI() + " objB2.objA.j- " + objB2.getObjA().getJ());

 }
}

Output

objB.x- 10 objB.objA.i- 100 objB.objA.j- 30
objB2.x- 1 objB2.objA.i- 100 objB2.objA.j- 30 

In CloningDemo class objB is cloned to get a new instance objB2. Value of primitive field x is changed in the cloned object objB2, you can see that both objects have their own independent values for field x.

Coming to object field, objB2 will have its own field objA where value of field i is changed. You can see that value in the original object objB for objA.i is also changed as the objA reference is shared between the objects. That’s one drawback of shallow copy.

Deep Copy in Java

When a deep copy is done objects referenced by the cloned object are distinct from those referenced by original object, and independent.

To create a deep copy while cloning an object you need to override clone method and call clone() method for even the objects referenced by the cloned object.

Deep copies are more expensive, as you need to create additional objects, and can be substantially more complicated, due to references possibly forming a complicated graph.

Deep copy Java example

Here we have a Class called ClassA with 2 int fields. Another class ClassB which has a ClassA object and an int field.

In classB, clone() method is overridden and clone method is explicitly called for the reference object objA too to get a separate copy of referenced object too.

class ClassA implements Cloneable{
  private int i;
  private int j;
  // Constructor
  public ClassA(int i, int j){
   this.i = i;
   this.j = j;
  }
  public void setI(int i) {
   this.i = i;
  }
  public void setJ(int j) {
   this.j = j;
  }
  public int getI() {
   return i;
  }
  public int getJ() {
   return j;
  }
  public Object clone() throws CloneNotSupportedException{
   return super.clone();
  }
}

class ClassB implements Cloneable{
  private int x;
  private ClassA objA;
  
  public ClassB(int x, ClassA objA){
   this.x = x;
   this.objA = objA;
  }
  public Object clone() throws CloneNotSupportedException{
   ClassB obj =  (ClassB) super.clone();
   // explicitly cloning classA object too
   obj.objA = (ClassA) objA.clone();
   return obj;
  }
  public int getX() {
   return x;
  }
  public ClassA getObjA() {
   return objA;
  }
  public void setX(int x) {
   this.x = x;
  }
  public void setObjA(ClassA objA) {
   this.objA = objA;
  }
}

public class CloningDemo {

 public static void main(String[] args) {
   ClassB objB = new ClassB(10, new ClassA(20, 30));
   
   ClassB objB2 = null;
   try {
    objB2 = (ClassB)objB.clone();
    
   } catch (CloneNotSupportedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   // value of field i of objA changed 
   // in cloned object
   objB2.getObjA().setI(100); 
   // Value of primitive field x changed 
   // in cloned object
   objB2.setX(1);
   System.out.println("objB.x- " +  objB.getX() + " objB.objA.i- " + objB.getObjA().getI() + " objB.objA.j- " + objB.getObjA().getJ());

   System.out.println("objB2.x- " +  objB2.getX() + " objB2.objA.i- " + objB2.getObjA().getI() + " objB2.objA.j- " + objB2.getObjA().getJ());

  }
}

Output

objB.x- 10 objB.objA.i- 20 objB.objA.j- 30
objB2.x- 1 objB2.objA.i- 100 objB2.objA.j- 30

Now the change to objA.i field in the cloned object is not reflected to the original object.

Shallow copy Vs Deep Copy in Java

  1. In case of shallow copy, primitive fields are created separately for the cloned object but any object reference is shared between the original and cloned object.
    In case of deep copy, separate copies of the referenced objects are also created so that original and cloned object are completely independent of each other.
  2. If class has only primitive fields shallow copy is the best choice.
    If class contains other objects then you need deep copy to have separate copies for the contained objects.
  3. Object cloning done by using Object class’ clone() method by default creates a shallow copy of an object.
    For creating a deep copy of any object you need to override the clone() method and provide the functionality to create separate copies of the reference objects too.
  4. Shallow copies are simple to implement and typically cheap, as they can be usually implemented by simply copying the bits exactly.
    Deep copies are expensive and more complicated because you may have to create a whole object graph for the cloned object.

That's all for this topic Shallow Copy And Deep Copy in Java Object Cloning. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Serialization and Deserialization in Java
  2. Nested Class And Inner Class in Java
  3. How to Pass Command Line Arguments in Eclipse
  4. Difference Between equals() Method And equality Operator == in Java
  5. BigDecimal in Java With Examples

You may also like-

  1. Just In Time Compiler (JIT) in Java
  2. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  3. AtomicInteger in Java With Examples
  4. HashMap Vs LinkedHashMap Vs TreeMap in Java
  5. EnumSet in Java With Examples
  6. Java Program to Find The Longest Palindrome in a Given String
  7. Spring Web MVC Tutorial
  8. Installing Hadoop on a Single Node Cluster in Pseudo-Distributed Mode

Tuesday, March 14, 2023

Service in Angular With Examples

A good design always advocates “Separation of concerns”, in Angular too that is desirable thus it is recommended that a Component should have only view-related functionality. Any application logic like fetching data through server calls, user input validation, logging to console should be delegated to a service in Angular.


Benefits of using Services in Angular

By delegating such tasks to services you have the following advantages.

  • Having lean components (concentrating only on enabling user experience).
  • Application logic in service classes that can be made available to any component thus promoting reusability.
Service in Angular

How to create a service in Angular

You can create an Angular service using following command.

ng generate service service_name

or you can use the short form of it.

ng g s service_name

For example if you want to create a service class logger inside services folder in your app directory.

ng g s services/logger

This will create logger.service.ts TypeScript file with in services folder.

Angular service example

Lets create the same logger service example. If you want to create your service classes with in a services folder then run the following command to create logger service.

ng g s services/logger

Angular CLI creates a logger.service.ts file and also do the following-

  1. Adds @Injectable decorator
  2. Registers a provider with the root injector
    @Injectable({
      providedIn: 'root'
    })
    
    

Add code for logging to console in the service class.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LoggerService {

  constructor() { }
  log(msg: string) { 
    console.log(msg); 
  }
  error(msg: string) { 
    console.error(msg); 
  }
}

Component class

Let’s create a component user.component.ts where we’ll use this LoggerService.

import { Component, OnInit } from '@angular/core';
import { User } from './user.model';
import { LoggerService } from '../services/logger.service';

@Component({
  selector: 'app-user',
  templateUrl: './',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
  users: User[];
  constructor(private loggerServcie: LoggerService) { 
    // Adding user instances in the users array
    this.users = [new User('Jack', 62, new Date('2005-03-25')),
                  new User('Olivia', 26, new Date('2014-05-09')),
                  new User('Manish', 34, new Date('2010-10-21'))] ;

    this.loggerServcie.log(`Total ${this.users.length} users in array.`);
  }

  ngOnInit(): void {
  }
}

In the constructor of the component you can see that an instance of LoggerService is created which is injected by the Angular (see the next section for more details about dependency injection). You also need to import the logger.service class.

Once the service instance is available that can be used to log a message, that’s what the following statement does in the code.

this.loggerServcie.log(`Total ${this.users.length} users in array.`);

Template (HTML file)

Let’s quickly create user.component.html file too which shows all the users in a table.

<div class="container">
  <h2>User Details</h2>
  <table class="table table-sm table-bordered m-t-4">
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Joining Date</th>
    </tr>
    <tr *ngFor="let user of users">
      <td>{{user.name}}</td>
      <td>{{user.age}}</td>
      <td>{{user.joinDate | date:'dd/MM/yyyy'}}</td>
    </tr>
  </table>
</div>

Now when you run it, you can see the message in the console.

Angular Service example

Service and dependency injection in Angular

You would have noticed in the example that Component class has a dependency on a LoggerService instance but that is not created explicitly. So you don’t see code as given below-

export class UserComponent implements OnInit {
  users: User[];
  loggerService: LoggerService; 
  constructor() { 
    this.loggerService = new LoggerService();
    ..
  }
..
}

Angular uses the concept of dependency injection to inject the dependencies. DI is a coding pattern in which class dependencies are injected rather than class creating them itself. In Angular, the DI framework provides declared dependencies to a class when that class is instantiated. The whole DI process in Angular can be explained in simple steps as follows-

  1. Create and register a dependency with Angular.
  2. Configure how the dependency instance is created and injected.
  3. Inject the dependency where needed.

1. Create and register a dependency with Angular

In case of providing Service as dependency first step is to create an injectable service class. To define a class as a service in Angular, decorate the class with @Injectable() decorator to provide the metadata that allows Angular to inject it into a component as a dependency.

2. Configure how the dependency instance is created and injected

Using @Injectable() decorator you just mark a service that can be injected. You also need to configure an Angular dependency injector with a provider of that service to actually inject a service.

The injector is responsible for creating service instances and injecting them into component classes. But you don't need to create injector yourself that is done by Angular itself and the first injector Angular creates is the 'root injector' that it creates during the bootstrap process.

A provider tells an injector how to create the service. You must configure an injector with a provider before that injector can create a service.

If we take our Service class there the @Injectable decorator is used like-

@Injectable({
  providedIn: 'root'
})
export class LoggerService {
..
..
}

@Injectable() decorator has the ‘providedIn’ metadata option, where provider of the decorated service class is specified as root injector.

When a service is provided at the root level, Angular creates a single, shared instance of the Service and injects it into any class that asks for it. So LoggerService is a singleton service and the same instance will be injected where it is asked for.

You can register a provider using other ways too. Check this post for other options- Injector Hierarchy and Service Instances in Angular

3. Inject the dependency

When you need a Service in a Component you ask for Service to be injected, rather than creating new instance yourself. You can tell Angular to inject a dependency in a component's constructor by specifying a constructor parameter with the dependency type.

That is why constructor in UserComponent has LoggerService type as parameter.

constructor(private loggerService: LoggerService)

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

>>>Return to Angular Tutorial Page


Related Topics

  1. Injector Hierarchy and Service Instances in Angular
  2. Angular - Call One Service From Another
  3. Angular Project Structure With File Description
  4. Creating New Component in Angular
  5. How to Add Bootstrap to Angular Application

You may also like-

  1. Angular CanActivateChild Guard to protect Child Routes
  2. Angular @Component Decorator
  3. Angular Custom Property Binding Using @Input Decorator
  4. Angular ngSwitch Directive With Examples
  5. Installing Anaconda Distribution On Windows
  6. @FunctionalInterface Annotation in Java
  7. Java ReentrantLock With Examples
  8. Spring WebFlux Example Using Annotation-Based Programming - Spring Web Reactive

Monday, March 13, 2023

String in Java Tutorial

This post talks about one of the very important class; String in Java. In Java String class represents character strings which means; Strings in Java are objects and all created strings are instances of the String class in Java. In String class strings are internally stored as character array.


How to create String in Java

You can create a String object using-

  • new operator
  • Using String literal

1. Using new operator

Since strings are objects so strings can of course be created using new operator. String class has more than 10 constructors to create Strings in Java which ranges from taking nothing as parameter to taking char array, StringBuffer, StringBuilder, another String as argument. For Example

String str = new String(“abc”);

2. Using String literal

Preferred way to create Strings is to assign String literal directly to a String reference as you will do for any primitive type. For every String literal Java automatically constructs a String object. For Example

String str = “abc”;

String pool in Java

But having String literals brings another dimension to storing String in Java. If String objects are created using new operator, objects will go in the heap with their own space. String literals are treated differently they are stored in a String pool and that is a common pool; which means if there are two strings literals having the same content then those string will share the space in the pool.

When String object is created by assigning a string literal, pool will be checked to verify if there is any existing object with the same content if there is then that existing reference is used, no new object is created in that case. If no object is found with the same content then this new literal will be added in the pool.

For example, if two strings str1 and str2 are created as follows-

String str1 = "abc";
String str2 = "abc";

Then the string object reference is shared between these two literals.

String pool in Java
String pool in Java

Let’s see it with an example

In this program two string literals will be created with the same content and then these two string objects are checked for reference equality. Since we are not comparing the content but the references of two objects so “==” operator will be used.

public class StringDemo {
 public static void main(String[] args) {
  String str1 = "abc";
  String str2 = "abc";
  if(str1 == str2){
   System.out.println("str1 and str2 are same");
  }else{
   System.out.println("str1 and str2 are not same");
  }
 }
}

Output

str1 and str2 are same

Refer String Pool in Java to know more about String pool.

Java String intern() method

Using Java String's intern() method you can still get string object from the pool (if it exists) even if new operator is used to create a string.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String  object is added to the pool and a reference to this String object is returned.

In the previous Java program if str4 is changed to have interned string then the code will look like–

public class StringDemo {

 public static void main(String[] args) {
  String str1 = "abc";
  String str2 = "abc";
  if(str1 == str2){
   System.out.println("str1 and str2 are same");
  }else{
   System.out.println("str1 and str2 are not same");
  }
  String str3 = new String("abc");
  String str4 = new String("abc").intern();
  if(str3 == str4){
   System.out.println("str3 and str4 are same");
  }else{
   System.out.println("str3 and str4 are not same");
  }
  
  if(str1 == str4){
   System.out.println("str1 and str4 are same");
  }else{
   System.out.println("str1 and str4 are not same");
  }
 }
}

Output

str1 and str2 are same
str3 and str4 are not same
str1 and str4 are same

It can be seen that str1 and str4 are having the same reference now.

Java String is immutable

Once you create a String object the content of that string cannot be modified. As we have already seen Java maintains a string pool where references are shared thus changing content of any of the String will also affect the other strings sharing the same references that’s one reason why String is immutable in Java.

Here being immutable means whenever you perform any operation on string which alters its content a new string object is created which contains the modified string. Original string is left as it is. If there are no references to the original string it is garbage collected.

Using any of the methods that modify the original String like toLowerCase, toUpperCase, concatenating using concatenate() method or ‘+’ operator will result in creation of a new string object.

Let's try to see the immutability of the String using as example.

String str = "hello";
str.concat("world");
System.out.println("Value of str- " + str);

Output

Value of str- hello

You can see that the original String is not changed, when the concatenation is done a new String object is created.

Refer Why is String Immutable in Java to know more about immutable strings and why are strings immutable in Java.

String class in Java is final

As already mentioned above whenever you perform any operation on string which alters its content a new string object is created containing the modified string. Which means all the methods of the String class in Java that modify the content in any way return a new String object with the modified content.

Now, what if you can override the method of the String class and provide an implementation to modify the content of the String and return the original String itself? What will happen to the String pool then where strings having the same data share the same reference?

Another scenario- You extend the String class and override hashCode() and equals() method in such a way that two dissimilar strings return the same hashCode and at the same time equals() return true. Then you can have different strings sharing the same reference in the String pool.

To avoid these kind of scenarios String class is declared as final in Java and it can’t be overridden.

String and thread-safety

Since String objects are immutable thus thread-safe.

Refer Is String Thread Safe in Java to know more about String and thread safety.

Overloaded operators in String

Apart from using concatenate method to concatenate two strings ‘+’ operator can be used to do the same. Actually + and += are two operators which are overloaded for String in Java.

So, if you have two strings
String str1 = "Hi";
String str2 = "Hello";

You can use ‘+’ operator to concatenate them

str1 = str1 + str2;
System.out.println("str1 " + str1);

Or, to make it more concise

str1 += str2;
System.out.println("str1 " + str1);

Comparing Strings using .equals method

In the section about string pool we used == to compare references but what if you want to compare content of two strings even if their references are different. You will have to use .equals method in that case.

public class StringDemo {

 public static void main(String[] args) {
  String str1 = "abc";
  String str4 = new String("abc");
  // comparing content
  if(str1.equals(str4)){
   System.out.println("str1 and str4 are same");
  }else{
   System.out.println("str1 and str4 are not same");
  }
  // comparing references
  if(str1 == str4){
   System.out.println("str1 and str4 are same");
  }else{
   System.out.println("str1 and str4 are not same");
  }
 }
}

Output

str1 and str4 are same
str1 and str4 are not same

Though str1 and str4 have same content but they will have different references as str4 is created using new operator. That is why comparing using "==" prints "str1 and str4 are not same" as references are different but comparing using .equals prints "str1 and str4 are same", as content is compared in that case.

Java String class methods

String class has lots of methods for various operations. These String class methods can be grouped as per functionality.

  1. Methods for String comparison- In Java String class there are methods like equals, compareTo, regionMatches for comparing strings. Refer String Comparison in Java to see examples of comparing strings in Java.
  2. Methods for searching in String- If you want to find characters or substrings within a String you can use methods like indexOf() and lastIndexOf(). Refer Searching Within a String Using indexOf(), lastIndexOf() And contains() Methods to see examples of searching with in a String.
  3. Getting specific character from String- If you are trying to get specific character from a String then you can use charAt() method. Refer Java String charAt() Method With Examples to see examples of getting characters from a String.
  4. Getting a substring- If you are trying to get substring with in a String then you can use substring() method. Refer Getting Substring - Java String substring() Method to see examples of getting substring from a String.
  5. Splitting a String- If you want to split a string into one or more substrings then you can use split() method. Refer Splitting a String Using split() Method in Java to see examples of splitting a String in Java.
  6. Merging Strings- For merging multiple strings in Java you can use join() method. Refer String join() Method in Java to see examples of joining Strings in Java.
  7. Checking String null or empty- For checking if the String is null or empty you can use isEempty(), length() or isBlank() method. Refer Check String Null or Empty in Java to see examples.
  8. intern() Method- For interning strings in Java you can use intern() method. Refer intern() Method in Java String to know more about interning Strings.
  9. matches() Method- Using matches() method you can check whether or not this string matches the given regular expression. Refer matches() method in Java String to see examples of matches() method.

Points to note about Java String

  1. Internally in String class, Strings are stored as character array.
  2. Strings in Java are objects and all strings are instances of the String class.
  3. Strings can be created by assigning String literal directly to a String reference like String str = “abc”; which may look like assigning to a primitive data type but don't forget Strings are objects.
  4. String literals in Java are treated differently, they are stored in a String pool and that is a common pool.
  5. If there are two strings literals having the same content then those string will share the space in the pool.
  6. String is immutable in Java once you create a String object the content of that string cannot be modified.
  7. Since String is immutable in Java whenever you perform any operation on string which alters its content a new string object is created which contains the modified string. Original string is left as it is.
  8. Since String is immutable it is also thread safe.
  9. String class is declared as final and it can’t be overridden.
  10. "+" operator is overloaded for String and it is used for concatenating strings.
  11. Using intern() method you can still get string object from the pool (if it exists) even if new operator is used to create a string.
  12. For comparing the content of two strings .equals() method is used. If you want to ignore case then use .equalsIgnoreCase().
  13. From Java 7 string can also be used in switch case statement.
  14. join() method is added in String class in Java 8 which makes it very easy to join multiple strings.

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

>>>Return to Java Basics Tutorial Page


Related topics

  1. StringBuffer Class in Java With Examples
  2. Converting Char to String And String to Char in Java
  3. Converting String to int in Java
  4. How to Create Immutable Class in Java
  5. Java String Interview Questions And Answers

You may also like-

  1. Marker interface in Java
  2. Array in Java With Examples
  3. How and why to synchronize ArrayList in Java
  4. LinkedHashMap in Java With Examples
  5. Java Exception Handling And Method Overriding
  6. finally Block in Java Exception Handling
  7. Java BlockingQueue With Examples
  8. Java ReentrantLock With Examples

Sunday, March 12, 2023

Converting Enum to String in Java

In this post we'll see the options we have to convert an Enum to String in Java. It may be needed when you want to compare Enum to String in Java.

Converting Enum to String in Java

Enum class in Java has two methods that can convert Enum to String.

  1. name()- Returns the name of this enum constant, exactly as declared in its enum declaration.
  2. toString()- Returns the name of this enum constant, as contained in the declaration.

As per Java docs toString() should be preferred. That’s what the description of the name() method says “Most programmers should use the toString() method in preference to this one, as the toString method may return a more user-friendly name”. This is because of the fact that toString() can be overridden if need be to return a more "programmer-friendly" string form.

Converting Enum to String using name() method

Following example shows how to convert Enum to String in Java using name() method. In the example Enum constants are iterated using the values() method, in each iteration Enum type is converted to String using the name() method.

public class EnumToString {
 private enum Day {
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
  THURSDAY, FRIDAY, SATURDAY 
 }
 public static void main(String[] args) {
  EnumToString ed = new EnumToString();
  ed.displayDays();
 }
 
 private void displayDays(){
  Day[] allDays = Day.values();
  for(Day d : allDays){
   String day =  d.name();
   System.out.println("Day of week- " + day);
  }
 } 
}

Output

Day of week- SUNDAY
Day of week- MONDAY
Day of week- TUESDAY
Day of week- WEDNESDAY
Day of week- THURSDAY
Day of week- FRIDAY
Day of week- SATURDAY

Converting Enum to String using toString() method

Following example shows how to convert Enum to String using toString() method. In the example toString() is overridden with in the Enum type to return a short form of the day. Note that it is not always required to override toString() method, here it is done just to demonstrate how it can be used to return a more "programmer-friendly" string form.

public class EnumToString {
 private enum Day {
  SUNDAY("Sun"), MONDAY("Mon"), TUESDAY("Tue"), WEDNESDAY("Wed"),
  THURSDAY("Thu"), FRIDAY("Fri"), SATURDAY("Sat");
  private String shortDay; 
  Day(String shortDay){
    this.shortDay = shortDay;
  }
  @Override
  public String toString() {
    return shortDay;
  }
 }
 
 public static void main(String[] args) {
  EnumToString ed = new EnumToString();
  ed.displayDays();
 }
 
 private void displayDays(){
  Day[] allDays = Day.values();
  for(Day d : allDays){
   String day =  d.toString();
   System.out.println("Day of week- " + day);
  }
 } 
}

Output

Day of week- Sun
Day of week- Mon
Day of week- Tue
Day of week- Wed
Day of week- Thu
Day of week- Fri
Day of week- Sat

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

>>>Return to Java Programs Page


Related Topics

  1. Converting String to Enum Type in Java
  2. Convert double to int in Java
  3. Convert Numbers to Words Java Program
  4. How to Convert a File to Byte Array
  5. How to Convert String to Date in Java

You may also like-

  1. Split a String Java Program
  2. Java Lambda Expression Comparator Example
  3. Java Program to Display Prime Numbers
  4. Printing Numbers in Sequence Using Threads Java Program
  5. Adding Tomcat Server to Eclipse
  6. Type Erasure in Java Generics
  7. Nested Class And Inner Class in Java
  8. Difference Between @Controller And @RestController Annotations in Spring

Saturday, March 11, 2023

Java Program to Find The Longest Palindrome in a Given String

This post is about writing a Java program to find the longest palindrome in a given String.

Logic for finding the longest palindrome in a given string

The solution given here works on the logic that in a palindrome, starting from the center, if two cursors are moved left and right respectively one character at a time, those values should be equal. This holds true if the length of the string is odd.

For example, if string is 121 then centre is 2. Character at the left and character at the right, if checked for equality should be equal. You can check for 24642, aba, malayalam.

If the length of the string is even then you have to take 2 characters as center, and then check the character at the left and character at the right for equality. Of course two characters considered as center should be equal too.

For example, if string is 1221, then centre is 22 from there you move one character to left and one character to right. You can check for toppot, abba.

Punctuation, capitalization, and spaces are usually ignored, in the given code it is not done though.

Note that this Java program is to find the longest palindrome in the given string. For example- bananas, in this string "ana", "ana" and "anana" three palindromes are present but the longest is "anana".

If you are looking for Java program to find whether given string is palindrome or not refer this link- Check if Given String or Number is a Palindrome Java Program

Java code for finding the longest palindromic String

public class PalDemo {

  public static void main(String[] args) {
    PalDemo pd = new PalDemo();
    
    String pal = pd.findLongestPalindrome("bananas");
    System.out.println("" + pal);
    
    pal = pd.findLongestPalindrome("abaradar121");
    System.out.println("" + pal);
  }
    
  public String findLongestPalindrome(String s) {
    // Validations
    if (s.isEmpty()) {
      return "Please enter a String";
    }

    if (s.length() == 1) {
      return s;
    }
    // Validations end
    // Start with one char (starting) as a longest palindrome
    String longest = s.substring(0, 1);
    for (int i = 0; i < s.length(); i = i+1) {        
      // get longest palindrome for odd length (center is i)
      String tmp = checkForEquality(s, i, i);
      if (tmp.length() > longest.length()) {
        longest = tmp;
      }

      // get longest palindrome for even length (center is i, i+1)
      tmp = checkForEquality(s, i, i + 1);
      if (tmp.length() > longest.length()) {
        longest = tmp;
      }
    }
    return longest;
  }
    
    
  /**
  * In this method equality is checked starting from
  * the center moving one character left and one character
  * right from the center. If both chars are equal then the
  * next set of chars are checked.  
  *     
  */
  public String checkForEquality(String s, int begin, int end) {
    while (begin >= 0 && end <= s.length() - 1 && s.charAt(begin) == s.charAt(end)) {
      begin--;
      end++;
    }
    return s.substring(begin + 1, end);    
  }
}
 

Output

anana
radar

Let's try to have a dry run with 121 as the entered string and trace the steps-

  1. After checking if String is empty or having just one character, first character of the string is stored as the longest.
  2. From the for loop, in the first call to method checkForEquality() entered String is passed as the first param. Other two params begin and end will be 0 and 0.
  3. In the while loop in the method checkForEquality(), begin >= 0 && end <= s.length() - 1 condition will pass as begin = 0 and end is less than 2 (length of string – 1). s.charAt(begin) == s.charAt(end) condition will also pass as both begin and end are pointing to same char. So begin has a value -1 and end has a value 1 now. With that while loop will fail.
    Only first char of the string will be returned as s.substring(begin + 1, end) will be translated as s.substring(0, 1) for begin = -1 and end = 1.
  4. Again checkForEquality() method will be called with 0 and 1 (this is to check for even case). With these values while loop will fail for the condition s.charAt(begin) == s.charAt(end) as both values will be different.
  5. Now i is 1, in that case s.charAt(begin) == s.charAt(end) condition will pass as value will be 2 for both. So begin-- gives begin = 0 and end++ gives end = 2. Again s.charAt(begin) == s.charAt(end) will pass as value will be 1 for both. So begin-- gives begin = -1 and end++ gives end = 3. With these values it will come out of while loop and returns s.substring(0, 3) which is 121.
  6. Since this returned value's length is greater than the current longest string so returned value becomes the longest.

Time complexity of the solution

Program given here to find the longest palindrome in a string in Java has a time complexity of O(N2), there is also a linear solution known as Manacher's algorithm

That's all for this topic Java Program to Find The Longest Palindrome in a Given String. 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. Count Number of Words in a String Java Program
  3. Add Double Quotes to a String Java Program
  4. Convert String to int in Java
  5. Print Odd-Even Numbers Using Threads And Semaphore - Java Program

You may also like-

  1. How to Format Date in Java Using SimpleDateFormat
  2. How to Read File From The Last Line in Java
  3. Abstraction in Java
  4. Race Condition in Java Multi-Threading
  5. Callable and Future in Java concurrency
  6. Java ReentrantLock With Examples
  7. Dependency Injection in Spring Framework
  8. Spring Component Scan to Automatically Discover Beans

Monday, March 6, 2023

Bean Definition Inheritance in Spring

In object-oriented programming there is a parent-child relationship among classes where child class inherits properties and methods of the parent class through inheritance. Same concept of inheritance is provided in Spring also where bean definition is inherited. In this post we'll learn about bean definition inheritance in Spring along with examples.

A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name and so on. So common things can be moved to one bean (parent bean) and other beans (child beans) can use it by inheriting that parent bean. A child bean definition inherits configuration data from a parent definition. In addition to that child definition can override some values, or add others, as needed.

Sunday, March 5, 2023

Angular Event Binding With Examples

In Angular one-way bindings, like property binding, attribute binding, flow is from Component to template but Angular event binding goes the other direction from template to component. Event binding allows you to listen and respond to certain events such as keystrokes, mouse movements, clicks, and touches sent by the host elements.

Angular event binding

Syntax of Angular event binding

Event binding is denoted by round brackets () and the syntax is as given below.

(event name) = "event handler expression/method"

Angular event binding syntax consists of a target event name within parentheses on the left of an equal sign, and a template statement with in quotes on the right.

For example-

Angular event binding syntax

Here event binding listens for the button's click events, calling the component's onSave() method whenever button is clicked.

Angular Even binding examples

1. First example shows how to disable a button after it is clicked. It uses both property and event binding. A boolean flag is bound to the “disabled” property of the button, when button is clicked using click event a method is called which toggles the boolean flag.

Component (Typescript code)

import { 
  Component
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  flag : boolean = false;
  // toggle the flag
  onButtonClick(){
    this.flag = !this.flag;
  }
}

Template (HTML file)

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <label for="name" class="col-form-label">Name:</label>
      <input class="form-control" placeholder="Enter name" id="name">        
    </div>
  </div>
  <div class="row mt-3">
    <div class="col-md-12">
      <button class="btn btn-primary" (click)="onButtonClick()" [disabled]="flag">Submit</button>
    </div>
  </div>
</div>

In the button element, click event is bound to a method onButtonClick(). When the button is clicked onButtonClick() method is called on the component which toggles the boolean flag field. Initially value of flag is false thus in the method it becomes true.

2. Binding with input event of input element to get the value of input field.

<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <label for="name" class="col-form-label">Name:</label>
      <input type="text" class="form-control" (input)="updateUserName($event)" id="name">            
    </div>
    <p>{{ userName }}</p>
  </div>
</div>

In the input element, input event is bound to a method updateUserName and $event is passed as an argument. $event denotes the data emitted with the event.

Component

import { 
  Component
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  userName : String;
  updateUserName(event : Event){
    this.userName = (event.target as HTMLInputElement).value;
  }
}

In the component there is a userName property, value from the passed $event argument is extracted in the method updateUserName() and assigned to the userName.

3. Using the mouseover event to display the selected item. In the example User records are displayed in a table and the user name over which mouse pointer is hovering is displayed in the separate <div> section using the mouseover event.

User Model class

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

Component

import { 
    Component
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  users: User[];
  userName : String;
  constructor(){
    // Adding User instances to users array
    this.users = [new User('Jack', 56, new Date('2005-03-25')),
    new User('Lisa', 32, new Date('2012-05-09')),
    new User('Jayesh', 28, new Date('2014-10-21'))] ;
  }
}

Template

<div class="container">
  <div class="bg-warning my-4">
    Selected User: {{userName || '(None)'}}
  </div>
  <table class="table table-sm table-bordered m-t-4">
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Joining Date</th>
    </tr>
    <tr *ngFor="let user of users">
      <td (mouseover)="userName=user.name">{{user.name}}</td>
      <td>{{user.age}}</td>
      <td>{{user.joinDate | date:'dd/MM/yyyy'}}</td>
    </tr>
  </table>
</div>

In the table (mouseover) event is used with the <td> element.

Build the example and run it, initial display should be as given below.

Angular even binding example

With mouse over selection.

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

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Two-Way Data Binding With Examples
  2. Angular One-Way Data Binding Using String Interpolation
  3. Angular Class Binding With Examples
  4. Angular Custom Property Binding Using @Input Decorator
  5. Angular Custom Event Binding Using @Output Decorator

You may also like-

  1. Angular Example to Render Multiple Rows
  2. Angular Template-Driven Form Validation Example
  3. How to Create a Custom Observable in Angular
  4. Angular ngSwitch Directive With Examples
  5. Shallow Copy And Deep Copy in Java Object Cloning
  6. String Pool in Java
  7. How to Fix The Target Type of This Expression Must be a Functional Interface Error
  8. Spring Boot Hello World Web Application Example

Friday, March 3, 2023

Java Program to Convert a File to Byte Array

There are times when we need to read file content into a byte array like when we need to send the file content over the network or we need to calculate check sum using file data. So in this post we'll see various ways to convert file to a byte array in Java.

Available options for conversion

  1. Using read method of the FileInputStream class. See example.
  2. Using Files.readAllBytes() method Java 7 onward. See example.
  3. Using IOUtils.toByteArray() method provided by Apache commons IO. See example.
  4. Using FileUtils.readFileToByteArray method provided by Apache commons IO. See example.

1. File to byte[] using read method of FileInputStream

You can use java.io.FileInputStream to read file content into a byte array using the read() method. General structure and description of read method as per Java docs is as given below.

public int read(byte[] b) throws IOException

Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

public class FileToByteArrayDemo {
  public static void main(String[] args) {
    File file = new File("F:\\NetJS\\Articles.txt");
    // Using java.io.FileInputStream
    byte[] bArray = readFileToByteArray(file);
    //displaying content of byte array
    for (int i = 0; i < bArray.length; i++){
      System.out.print((char) bArray[i]);
    }  
  }
    
  /**
   * This method uses java.io.FileInputStream to read
   * file content into a byte array
   * @param file
   * @return
   */
  private static byte[] readFileToByteArray(File file){
    FileInputStream fis = null;
    // Creating a byte array using the length of the file
    // file.length returns long which is cast to int
    byte[] bArray = new byte[(int) file.length()];
    try{
      fis = new FileInputStream(file);
      fis.read(bArray);
      fis.close();                   
    }catch(IOException ioExp){
      ioExp.printStackTrace();
    }
    return bArray;
  }
}

2. File to byte array conversion using Files.readAllBytes()

Java 7 onward you can use static method readAllBytes(Path path) in the Files class for converting file to byte array.

public class FileToByteArrayDemo {
  public static void main(String[] args) {              
    Path path = Paths.get("F:\\NetJS\\Articles.txt");
    try {
      byte[] bArray = Files.readAllBytes(path);
      // reading content from byte array
      for (int i = 0; i < bArray.length; i++){
        System.out.print((char) bArray[i]);
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }       
  }
}

3. Using IOUtils.toByteArray() and FileUtils.readFileToByteArray() methods

Apache commons IO also provides utility methods to read file content into a byte array.

  • IOUtils.toByteArray- Takes FileInputStream object as param.
  • FileUtils.readFileToByteArray- Takes File object as param.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class FileToByteArrayDemo {
  public static void main(String[] args) {
    File file = new File("F:\\NetJS\\Articles.txt");        
    // Using ApacheCommons methods
    readToByteArrayUsingCommons(file);     
  }
    
  /**
   * This method uses apache commons to read
   * file content into a byte array
   * @param file
  */
  private static void readToByteArrayUsingCommons(File file){
    try(FileInputStream fis = new FileInputStream(file)) {
      // Using IOUtils method, it takes FileInputStream 
      // object as param
      byte[] bArray = IOUtils.toByteArray(fis);
      for (int i = 0; i < bArray.length; i++){
        System.out.print((char) bArray[i]);
      }
      // Using FileUtils method, it takes file object
      // as param
      bArray = FileUtils.readFileToByteArray(file);
      //displaying byte array content
      for (int i = 0; i < bArray.length; i++){
        System.out.print((char) bArray[i]);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }        
  }
}

Note that in the method readToByteArrayUsingCommons I have used try-with-resources which is available from Java 7. Closing the input stream will be done automatically by try-with-resources.

Refer try-with-resources in Java 7 to know more about try-with-resources.

That's all for this topic Java Program to Convert a File to Byte Array. 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 BufferedReader
  3. How to Read Input From Console in Java
  4. Write to a File in Java
  5. Unzip File in Java

You may also like-

  1. Convert String to Byte Array Java Program
  2. Count Number of Words in a String Java Program
  3. How to Remove Elements From an Array Java Program
  4. Java Program to Check Prime Number
  5. final Keyword in Java With Examples
  6. How to Loop Through a Map in Java
  7. Java ReentrantLock With Examples
  8. Dependency Injection in Spring Framework

Thursday, March 2, 2023

ConcurrentSkipListSet in Java With Examples

ConcurrentSkipListSet in Java is a scalable concurrent set in Java which uses ConcurrentSkipListMap internally. Though concurrent collections like ConcurrentHashMap and CopyOnWriteArraySet were added in Java 1.5, ConcurrentSkipListSet and the similar map implementation ConcurrentSkipListMap were added in Java 1.6.

ConcurrentSkipListSet in Java

Since ConcurrentSkipListSet implements NavigableSet in Java, it is a sorted set just like TreeSet with added feature of being concurrent. Which essentially means it is a sorted data structure which can be used by multiple threads concurrently where as TreeSet is not thread safe.

The elements of the ConcurrentSkipListSet are kept sorted according to their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

Java ConcurrentSkipListSet constructors

  • ConcurrentSkipListSet()- Constructs a new, empty set that orders its elements according to their natural ordering.
  • ConcurrentSkipListSet(Collection<? extends E> c)- Constructs a new set containing the elements in the specified collection, that orders its elements according to their natural ordering.
  • ConcurrentSkipListSet(Comparator<? super E> comparator)- Constructs a new, empty set that orders its elements according to the specified comparator.
  • ConcurrentSkipListSet(SortedSet<E> s)- Constructs a new set containing the same elements and using the same ordering as the specified sorted set.Paste your text here.

Java ConcurrentSkipListSet performance

ConcurrentSkipListSet implementation provides expected average log(n) time cost for the contains, add, and remove operations and their variants. Insertion, removal, and access operations safely execute concurrently by multiple threads.

No Nulls in ConcurrentSkipListSet

ConcurrentSkipListSet does not permit the use of null elements, because null arguments and return values cannot be reliably distinguished from the absence of elements.

ConcurrentSkipListSet Java example

Let's see an example where we add some values in a ConcurrentSkipListSet and in the output it can be seen that the elements are sorted. In this example elements are of type String and for String natural ordering is ascending alphabetical order. So when you iterate the set you'll see it is in sorted same way.

Note that ConcurrentSkipListSet like any other set implementation i.e. HashSet can only store unique elements. Also, as mentioned internally it uses ConcurrentSkipListMap so when you call add method of ConcurrentSkipListSet it will in turn call putIfAbsent() method of the concurrentMap, that way element is stored only if it is not there already.

import java.util.Iterator;
import java.util.NavigableSet;
import java.util.concurrent.ConcurrentSkipListSet;

public class CSSDemo {
  public static void main(String[] args) {
    NavigableSet<String> citySet = new ConcurrentSkipListSet<String>();
    citySet.add("New Delhi");
    citySet.add("Mumbai");
    citySet.add("Chennai");
    citySet.add("Hyderabad");
    
    System.out.println("---- Traversing the set-----");
    Iterator<String> itr = citySet.iterator();
    while(itr.hasNext()){
      System.out.println("Value -  " + itr.next());
    }
  }
}

Output

---- Traversing the set-----
Value -  Chennai
Value -  Hyderabad
Value -  Mumbai
Value -  New Delhi

Navigable methods in ConcurrentSkipListSet

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

  • higher(E e)- Returns the least element in this set strictly greater than the given element, or null if there is no such element.
  • lower(E e)- Returns the greatest element in this set strictly less than the given element, or null if there is no such element.
  • tailSet(E fromElement)- Returns a view of the portion of this set whose elements are greater than or equal to fromElement.
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

public class CSSDemo {
  public static void main(String[] args) {
    NavigableSet<String> citySet = new ConcurrentSkipListSet<String>();
    citySet.add("New Delhi");
    citySet.add("Mumbai");
    citySet.add("Chennai");
    citySet.add("Hyderabad");
    
    System.out.println("---- Traversing the set-----");
    Iterator<String> itr = citySet.iterator();
    while(itr.hasNext()){
      System.out.println("Value -  " + itr.next());
    }
        
    System.out.println("Higher - " + citySet.higher("C"));    
    System.out.println("Lower - " + citySet.lower("Mumbai"));    
    System.out.println("---- Tail Set -----");
    
    Set<String> set = citySet.tailSet("Hyderabad");    
    itr = set.iterator();
    while(itr.hasNext()){
      System.out.println("Value -  " + itr.next());
    }
  }
}

Output

---- Traversing the set-----
Value -  Chennai
Value -  Hyderabad
Value -  Mumbai
Value -  New Delhi
Higher - Chennai
Lower - Hyderabad
---- Tail Set -----
Value -  Hyderabad
Value -  Mumbai
Value -  New Delhi

Here higher as the description says is returning the least element in this set strictly greater than the given element. Since given element is "C" so returned value is "Chennai". Note that passed element doesn't have to be the one already present in set as here "C" is passed which is not an element of the Set.

lower as the description says is returning the greatest element in this set strictly less than the given element. Passed element is "Mumbai" so that returned element is "Hyderabad".

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


Related Topics

  1. ConcurrentHashMap in Java With Examples
  2. CopyOnWriteArraySet in Java With Examples
  3. Java ArrayBlockingQueue With Examples
  4. Java CountDownLatch With Examples
  5. Java Concurrency Interview Questions And Answers

You may also like-

  1. How to Sort Elements in Different Order in TreeSet
  2. How to Sort HashSet in Java
  3. Difference Between Comparable and Comparator in Java
  4. Interface Default Methods in Java
  5. Java ThreadLocal Class With Examples
  6. Deadlock in Java Multi-Threading
  7. static Import in Java With Examples
  8. Difference Between throw And throws in Java

Wednesday, March 1, 2023

Map Operation in Java Stream API

Map operations in Java Stream API, as the name suggests, are used to do the element mapping from one stream to another. Map operation will return a stream consisting of the results of applying the given function to the elements of this stream. So, whatever function is provided is applied on all the elements of the stream.

One thing to note here is; since new stream is returned map operation is an intermediate operation.

map method in Java Stream

Java stream API provides the following map method.

<R> Stream<R> map(Function<? super T,? extends R> mapper)- Returns a stream consisting of the results of applying the given function to the elements of this stream.

Here R is the element type of the new stream, T denotes the element type of the existing stream and mapper is the function which will be applied to all the elements of the stream.

Here note that mapper is an instance of Function which is a functional interface. Since it is a functional interface therefore it can be used as the assignment target for a lambda expression or method reference.

map() method examples in Java Stream

  1. You have a stream of some names and you want to get a list where names are stored in upper case. In that case using map() method you can apply a function to all the elements of the stream to convert those elements to upper case and then using collector, collect them in a list.
    public class MappingDemo {
      public static void main(String[] args) {
        List<String> nameList = Stream.of("amy", "nick", "margo", "desi")
                                            .map(s->s.toUpperCase())
                                            .collect(Collectors.toList());
        System.out.println("Names in upper case" + nameList);
    
      }
    }
    

    Output

    Names in upper case[AMY, NICK, MARGO, DESI]
    
  2. You have a list of salaries and you want to increase salaries by 10%.
    List<Integer> myList = Arrays.asList(7000, 5000, 4000, 24000, 17000, 6000);  
    myList.stream().map(i -> (i+ (i * 10/100))).forEach(System.out::println);
    

    Output

    7700
    5500
    4400
    26400
    18700
    6600
    
  3. There is an employee class and you want the name of all the female employees. In this example you can use filter() method to filter female employees and then using map() method you can get the name of those employees. Here using map() method you are transforming employee object to String object.
    public class MappingDemo {
    
      public static void main(String[] args) {
        MappingDemo md = new MappingDemo();
        List<Employee> empList = md.createList();
        System.out.println("--- Name of female employees ---");
        empList.stream()
               .filter(e -> (e.getSex() == 'F'))
               .map(e -> e.getName())
               .forEach(System.out::println);
    
      }
        
      // Stub method to create list of employee objects
      private List<Employee> createList(){
        List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                                       new Employee("E002", 35, "Sheila", 'F', 7000), 
                                       new Employee("E003", 24, "Mukesh", 'M', 9000), 
                                       new Employee("E004", 37, "Rani", 'F', 10000));
        
        return empList;
      }
      
      class Employee {
        private String empId;
        private int age;
        private String name;
        private char sex;
        private int salary;
        Employee(String empId, int age, String name, char sex, int salary){
          this.empId = empId;
          this.age = age;
          this.name = name;
          this.sex = sex;
          this.salary = salary;
        }
        public String getEmpId() {
          return empId;
        }
        public void setEmpId(String empId) {
          this.empId = empId;
        }
        public int getAge() {
          return age;
        }
        public void setAge(int age) {
          this.age = age;
        }
        public String getName() {
          return name;
        }
        public void setName(String name) {
          this.name = name;
        }
        public char getSex() {
          return sex;
        }
        public void setSex(char sex) {
          this.sex = sex;
        }
        public int getSalary() {
          return salary;
        }
        public void setSalary(int salary) {
          this.salary = salary;
        }       
      }
    }
    

    Output

    --- Name of female employees ---
    Sheila
    Rani
    

Variants of map() method

There are three variants of map() method which return a primitive stream.

  • mapToInt(ToIntFunction<? super T> mapper)- Returns an IntStream consisting of the results of applying the given function to the elements of this stream.
  • mapToDouble(ToDoubleFunction<? super T> mapper)- Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.
  • mapToLong(ToLongFunction<? super T> mapper)- Returns a LongStream consisting of the results of applying the given function to the elements of this stream.

Apart from that, in all the primitive type streams– IntStream, LongStream and Double Stream there is also a mapToObj() method.

For IntStream mapToObj() function is defined like this-

  • mapToObj(IntFunction<? extends U> mapper)- Returns an object-valued Stream consisting of the results of applying the given function to the elements of this stream.

map() method with primitive streams examples

  1. If you want to get the total of salaries for the employees (Using the employee class as above), you can use mapToInt() method to get an IntStream consisting of salaries and then apply sum() method on that int stream.
    int totalSalary = empList.stream().mapToInt(e -> e.getSalary()).sum();
    System.out.println("total of salaries " + totalSalary);
    

    Output

    total of salaries 31000
    
  2. If you want to get the maximum salary, you can use mapToInt() method to get an IntStream consisting of salaries and then apply max() method on that int stream to get the maximum salary.
    OptionalInt maxSalary = empList.stream().mapToInt(e -> e.getSalary()).max();
    if(maxSalary.isPresent()){
        System.out.println("Maximum Salary " + maxSalary.getAsInt());
    }
    

    Output

    Maximum Salary 10000
    
  3. For your testing you want to create 500 objects of some class -
    List<Employee> empList = IntStream.rangeClosed(1, 500).mapToObj(Employee::new).collect(Collectors.toList());
    

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

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream API Tutorial
  2. Parallel Stream in Java Stream API
  3. collect() Method And Collectors Class in Java Stream API
  4. Reduction Operations in Java Stream API
  5. @FunctionalInterface Annotation in Java

You may also like-

  1. New Date And Time API in Java With Examples
  2. Effectively Final in Java 8
  3. How HashMap Works Internally in Java
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. Difference Between CountDownLatch And CyclicBarrier in Java
  6. Java ReentrantLock With Examples
  7. Find All Permutations of a Given String Java Program
  8. Spring Component Scan Example