Thursday, 27 July 2023

Strategy Design Pattern

       In this post, we need to learn Strategy Design pattern with real time examples. For all design pattern posts refer - Design Patterns
      
      Strategy design pattern is one of the behavioral design pattern. Strategy pattern is used when we have multiple algorithms for a specific task and client decides the actual implementation to be used at runtime. Strategy pattern provides more flexibility, extensibility, and choice.

     There are many real time examples like payment implementation for different payment types,  different sorting algorithms and many more.

     I will take a GST tax example and will discuss in more detail with code, so GST tax varies between each products. There are four slabs - 5% GST, 12%GST, 18% GST and 28% GST(currently it's four slabs, it might change in future) and some of products doesn't have GST I mean it's a zero slab, but for code implementation we are not considering that. 

      Instead of creating and writing logic in four different classes for each slab, we need to follow the Strategy design pattern it's more flexible, readable and reusable code and also it follows the  OOP's design principle.

First step is to create a interface and then for each slab need to create seperate class and implements the interface.

TaxCalculation.java

public interface TaxCalculation {
     public Double calculateTax(Double productPrice);
}

Implemented classes, the overriden method calculateTax method logic will differ for each slab.

FivePercentageTax.java

public class FivePercentageTax implements TaxCalculation{

	@Override
	public Double calculateTax(Double productPrice) {
		return (productPrice * 5) / 100;
	}

}

TwelvePercentageTax.java

public class TwelvePercentageTax implements TaxCalculation{

	@Override
	public Double calculateTax(Double productPrice) {
		return (productPrice * 12) / 100;
	}

}

EighteenPercentageTax.java

public class EighteenPercentageTax implements TaxCalculation {

	@Override
	public Double calculateTax(Double productPrice) {
		return (productPrice * 18) / 100;
	}

}

TwentyEightPercentageTax.java

public class TwentyEightPercentageTax implements TaxCalculation {

	@Override
	public Double calculateTax(Double productPrice) {
		return (productPrice * 28) / 100;
	}

}

The below class - GSTTaxCalculator is the main class where I created a method calculateGSTTax, in this need to pass the TaxCalculation implemented class object and using object we can call the claculateTax method it should invoke corresponding tax implementation method.

GSTTaxCalculator.java

public class GSTTaxCalculator {
	
     public double taxAmount;

     public void calculateGSTTax(TaxCalculation taxCalculation, double productPrice) {
	   this.taxAmount = taxCalculation.calculateTax(productPrice);
     }
}

StrategyDesignPatternDemo.java is a demo class to show the Strategy design outcome. So in your code implemention you just need to invoke above class - GSTTaxCalculator method using object and pass TaxCalculation implemented class object and also to pass the item price, it's just an example. We need to implement the Strategy Design pattern as per your requirement and scenario's.

StrategyDesignPatternDemo.java

public class StrategyDesignPatternDemo {
	
	public static void main(String[] args) {
		
		GSTTaxCalculator gstTaxCalculator = new GSTTaxCalculator();
		
		gstTaxCalculator.calculateGSTTax(new FivePercentageTax(), 250);
		System.out.println("GST tax for 5% slab - "+gstTaxCalculator.taxAmount);
		
		gstTaxCalculator.calculateGSTTax(new TwelvePercentageTax(), 250);
		System.out.println("GST tax for 12% slab - "+gstTaxCalculator.taxAmount);
		
		gstTaxCalculator.calculateGSTTax(new EighteenPercentageTax(), 250);
		System.out.println("GST tax for 18% slab - "+gstTaxCalculator.taxAmount);
		
		gstTaxCalculator.calculateGSTTax(new TwentyEightPercentageTax(), 250);
		System.out.println("GST tax for 28% slab - "+gstTaxCalculator.taxAmount);
	}
}

Output:- GST tax for 5% slab - 12.5
              GST tax for 12% slab - 30.0
              GST tax for 18% slab - 45.0
              GST tax for 28% slab - 70.0


Thank you for visiting the blog.

Tuesday, 25 July 2023

Publicis Sapient Java Technical Lead Interview questions

      Below are the list of java technical lead interview questions asked in Publicis Sapient during the second round.

1)  Time complexity for HashMap, LinkedHashMap, ArrayList, LinkedList, ConcurrentHashMap.(Answer)

2) Explain ReentrantLock in java (Answer)

3) What is thread pool and explain the executor framework.

4) Explain java 8 features(Answer)

5) What is difference between map and flatMap method in stream(Answer)

6) What is the difference between stream and parallel stream. Explain parallel stream performance.

7) What is association and aggregation in java(Answer)

8)  Explain Solid Design Principles(Answer)

9) Difference between SOA and Microservices (Answer)

10) Explain Design pattern used in Microservices mainly Circuit design pattern and Saga pattern(Answer)

11) How to communicate two microservices ? (Answer)

12) Difference between Kafka and RabitMQ(Answer)

13) Explain the scope of spring beans (Answer)

14) What is the use of spring actuator? (Answer)

15) Explain Spring security used in application(Answer)

16) Explain if you used any cahcing algorithm in application

17) Which annotations included in @SpringBootApplication (Answer)


Thank you for reading the blog.


Reference Posts:-

Monday, 24 July 2023

Java 8 Stream Coding Interview questions and answers

      Before attending any interview need to look into the Stream coding questions beacuse Stream API is an important topic in java 8.

Below are the java 8 stream coding questions and answers.

1) Write a program to print the list of elements from a list using java 8 stream

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
              List<String> list = Arrays.asList(new String[] {"ABC", "BCD", "CDE"});
	      list.stream().forEach(s -> System.out.println(s));
	}
}

Output:- ABC
              BCD
              CDE

2) Write a program to convert lowercase string element of a list into uppercase.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
     public static void main(String[] args) {
	   List<String> list = Arrays.asList(new String[] {"Abc", "bcd", "cde"});
	   list.stream().map(s-> s.toUpperCase()).forEach(
				s -> System.out.println(s));
     }
}

Output:- ABC
              BCD
              CDE

3) Print a list of strings those start with letter "A" and return updated list.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
		List<String> list = Arrays.asList(new String[] {"Abc", "bcd", "cde"});
		List<String> updatedList = list.stream().filter(s-> s.startsWith("A"))
				.collect(Collectors.toList());
		updatedList.stream().forEach(s -> System.out.println(s));
	}
}

Output:- Abc

4) Write a code to calculate the summation of the integers from the list.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(new Integer[] {1,2,3, 4,5});
		//Using lambda expression
		Integer sum = list.stream().mapToInt(i -> i).sum();
		System.out.println(sum);
		
		//Using Integer valueOf method
		Integer sumOfIntegers = list.stream().mapToInt(Integer::valueOf).sum();
		System.out.println(sumOfIntegers);
		
		//Using Integer intValue method
		Integer sumOfIntegerValue = list.stream().mapToInt(Integer::intValue).sum();
		System.out.println(sumOfIntegerValue);	
	}
}

Output:- 15
              15
              15

5) Create a Map object from List using Stream API

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
		List<String> list = Arrays.asList(new String[] {"Ab", "Bcd", "Ce"});
		Map<String, Integer> map = list.stream().collect(Collectors.toMap(
				s->s, s->s.length()));
		map.forEach((x,v) -> System.out.println("key - "+x+", value - "+v));
	}
}

Output:-
key - Ab, value - 2
key - Ce, value - 2
key - Bcd, value - 3

6) Write a program to list the distinct integers from list or remove duplicates from the list.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(new Integer[] {1, 2, 1,4});
		List<Integer> listWithDistinct = list.stream().distinct().collect(Collectors.toList());
		listWithDistinct.stream().forEach(s-> System.out.println(s));
	}
}

Output:-1
             2
             4

7) Write a program to find the Minimum number from a Stream/list.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
	     List<Integer> list = Arrays.asList(new Integer[] {1, 2,3,4});
	     Integer minNumber = list.stream().mapToInt(s->s).min().getAsInt();
	     System.out.println(minNumber);
	}
}

Output:-1

8) Write a program to find the Maximum number from a Stream/list.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
	     List<Integer> list = Arrays.asList(new Integer[] {1, 2,3,4});
	     Integer maxNumber = list.stream().mapToInt(s->s).max().getAsInt();
	     System.out.println(maxNumber);
	}
}

Output:-4

9) Write a program to sort the given list using java 8 stream.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
	     List<Integer> list = Arrays.asList(new Integer[] {8, 2,3,4});
	     List<Integer> sortedList = list.stream().sorted().collect(Collectors.toList());
	     sortedList.stream().forEach(s-> System.out.println(s));
	}
}

Output:-2
             3
             4
             8

10) Write a program to sort the given list in descending order using stream.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(new Integer[] {8, 2,3,4});
		List<Integer> sortedList = list.stream().sorted(
				Collections.reverseOrder()).collect(Collectors.toList());
		sortedList.stream().forEach(s-> System.out.println(s));
	}
}

Output:-8
             4
             3
             2

11) Write a program to count the total number of integers in the list.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
	     List<Integer> list = Arrays.asList(new Integer[] {8, 2,3,4});
	     long count = list.stream().count();
	     System.out.println(count);
	}
}

Output:-4

12)  Convert List<List<String>> into List<String> using flatMap method.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
	     List<List<Integer>> listListOfStrings = new ArrayList<List<Integer>>();
	     List<Integer> list = Arrays.asList(new Integer[] {8, 2,3,4});
	     listListOfStrings.add(list);
	     //use flatMap method
	     List<Integer> newList = listListOfStrings.stream().flatMap(
				s-> s.stream()).collect(Collectors.toList());
	     newList.stream().forEach(s-> System.out.println(s));
	}
}

Output:-8
             2
             3
             4

13) Group by a list element and display the total count of the element using Collectors groupingBy method.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
	     List<String> letters = Arrays.asList("A", "B", "C","A", "D", "C", "D");
	     Map<String, Long> mapWithLetterCount = letters.stream().collect(
	                        Collectors.groupingBy(
	                                Function.identity(), Collectors.counting()));  
	     System.out.println(mapWithLetterCount);   
	}
}

Output:- {A=2, B=1, C=2, D=2}

14)  Find the first element from the given list using java 8 stream.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
	     List<String> letters = Arrays.asList("A", "B", "C","A", "D", "C", "D");
	     String firstElement = letters.stream().findFirst().orElse("Default");  
	     System.out.println(firstElement);   
	}
}

Output:-A

15)  anyMatch code example - if any one of the list element matches with given character "A" then return true.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
             List<String> letters = Arrays.asList("A", "B", "C", "D");
	     boolean foundElement = letters.stream().anyMatch(s-> s.equalsIgnoreCase("A"));  
	     System.out.println(foundElement);   
	}
}

Output:-true

16) allMatch code example - if all of the elements matches with the given element say "A" then return true else false.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
             List<String> letters = Arrays.asList("A", "B", "C", "D");
	     boolean foundMatches = letters.stream().allMatch(s-> s.equalsIgnoreCase("A"));  
	     System.out.println(foundMatches);   
	}
}

Output:-false

17) Write a program to remove the duplicates from the list using Collectors toSet method.

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
	     List<String> letters = Arrays.asList("A", "B", "C", "D", "A", "B");
	     Set<String> nonDuplicateSet = letters.stream().collect(Collectors.toSet());  
	     nonDuplicateSet.stream().forEach(s-> System.out.println(s));
	}
}

Output:-A
             B
             C
             D

     
Thank you for reading the post.

Reference Posts:-

Wednesday, 19 July 2023

Difference between map and flatMap method in Java Stream

     A Stream API is an important feature introduced in java 8, Stream is not a data structure means not stores any data and also not modifying the data but it will operate with the data source and to process data in convenient and faster. Stream API is a cleaner and more readable code.

Let us discuss the map and flatMap method usages and differences.

Use a map() of stream method if you just want to transform one Stream into another where each element gets converted to one single value. 

Use flatMap() of stream method if the function used by map operation returns multiple values and you want just one list containing all the values of the lists.

map method code example,

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamMapExamples {
	
	public static void main(String[] args) {
		
		List<String> listOfStrings = Arrays.asList(new String[]{"abc", "bcd", "cde"});
		
		List<String> list = listOfStrings.stream()
				.map( s-> s.toUpperCase()).collect(Collectors.toList());
		
		list.stream().forEach(s-> System.out.println(s));
	}
	
}

the above code will print ABC, BCD and CDE.

flatMap code example,

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamflatMapExample {
	
	public static void main(String[] args) {
		
		List<List<String>> listListOfStrings = new ArrayList<List<String>>();
		listListOfStrings.add(Arrays.asList(new String[]{"ABC", "BCD"}));
		listListOfStrings.add(Arrays.asList(new String[]{"CDE", "DEF"}));
		
		List<String> listOfStrings = listListOfStrings.stream().flatMap(s->s.stream()).collect(Collectors.toList());
		
		listOfStrings.stream().forEach(s-> System.out.println(s));
	}

}

The flatMap method converts list of strings of list into list of strings, the above code will print ABC, BCD, CDE and DEF.