Skip to main content

Posts

Showing posts from October, 2019

Prime Anagrams - Comparing Anagrams using Prime Numbers

Introduction In this post, we will use prime numbers to compare anagrams. We will assign the prime number to each character in a string and then multiply them. Two strings will be equal if their product is the same. Implementation in Java public class PrimeAnagram { static int [] alphaPrime = {5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107}; static String alphabets = "abcdefghijklmnopqrstuvwxyz"; public static void main(String[] args) { System.out.println(isPrimeAnagram("parse", "spare")); } private static boolean isPrimeAnagram(String value1,String value2) { return getPrime(value1) == getPrime(value2); } private static int getPrime(String value) { value = value.toLowerCase(); int productValue = 1; for(int index = 0; index < value.length(); index++) { productValue *= alphaPrime[ alphabets.indexOf(value.charAt(index)) ]; } return productValue; } } Conclusion We

Often asked interview question to write code of Singleton Pattern?

Introduction I have been often asked this question in an interview to write a code of Singleton pattern. I have noticed that developers have the knowledge of what is Singleton pattern but often they forget the key points regarding its implementation. In this post, I will highlight the key points to remember for your upcoming interview. Implementation public class Singleton { private static Singleton instance; private Singleton() { } public static synchronized Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } } Key Points to remember a) instance is declared as private and static  b) The constructor is declared as private c) getInstance method is static and synchronized to make it thread free Conclusion In this post, we learned how to implement the Singleton pattern using Java language. We have also noted down the key points to remember.Please leave your comments in the comments box.

Solution of popular FizzBuzz coding puzzle in Java language

Introduction FizzBuzz is one of the popular coding puzzles asked in a programming interview. In this post, we will learn its implementation using Java 8. Problem We have 1 to n Integers. Write a program that iterates over these integers, print Fizz if Integer is multiple of 3, print Buzz if Integer is multiple of 5, print FizzBuzz if Integer is multiple of both 3 and 5 else print the Integer.  Solution import java.util.stream.IntStream; public class FizzBuzz { public static void main(String[] args) { int n = 100; IntStream.range(1, n).forEach( i -> { /* if( i % 3 == 0 && i % 5 == 0 ) is equivalent to i % 15 == 0 * and will reduce lines of code */ if( i % 15 == 0) { System.out.println("FizzBuzz"); }else if ( i % 3 == 0) { System.out.println("Fizz"); }else if ( i % 5 == 0) { System.out.println("Buzz"); }else { System.out.println(i); } }); } } Note that multiple of 15 is mult

How to sort collections in Java 8?

Introduction In this post, we will explore different ways to sort Java collections in a certain order. Java platform provides a  Collections framework that represents a group of objects. All the Java classes those implement the Collection interface have by default implemented the sort method i.e. Collections.sort(list/set/Array) Java classes like String, Date, Integer, Double, Float, Long, Integer etc implements the Comparable interface by default. Java provides us with the following two interfaces to compare and sort the custom objects Comparable Interface  public interface Comparable<T> { public int compareTo(T o); } Java 8 also provides the built in Comparator.comparing method that returns an instance of Comparable. Comparator Interface public interface Comparator<T> { int compare(T o1, T o2); } In this post we will use the following student class for practice. public class Student{ public String name; public Integer age; public St

Java - How to sort String in alphabetical order?

Introduction In this post, we will learn the following two examples a) Sort single String in alphabetical order b) Sort array of Strings Sort single String in alphabetical order import java.util.Arrays; public class SortStringAlphabetical { private static String inputString = "The quick brown fox jumps over the lazy dog"; public static void main(String[] args) { System.out.println("Input String : " + inputString); char [] characters = inputString.toCharArray(); Arrays.sort(characters); System.out.println("Alphabetical sorted String : " + new String(characters)); } } Output Input String : The quick brown fox jumps over the lazy dog Alphabetical sorted String :         Tabcdeeefghhijklmnoooopqrrstuuvwxyz Sort array of Strings import java.util.Arrays; public class SortStringArrayAlphabetical { private static String inputStrings[] = {"efg","xyz","abc"}; public static void ma

Hibernate 5.4.4 - How to fix hibernate depreciation warnings?

Problem Recently we migrated Hibernate to the latest version i.e. 5.4.4. Multiple depreciation warnings appeared in our code i.e. The type Query<R> is deprecated The method setString(String, String) from the type Query is deprecated The method uniqueResult() from the type Query is deprecated The method setBoolean(String, boolean) from the type Query is deprecated The method setLong(String, long) from the type Query is deprecated Solution Existing Change To import org.hibernate.Query; import org.hibernate. query .Query; query . setLong ( "serviceId" , serviceId ) ; query . setParameter ( "serviceId" , serviceId ); query . setBoolean ( "isDelete" ,Boolean. FALSE ) ; query . setParameter ( "isDelete" ,Boolean. FALSE ) ; query . setString ( "serviceNo" , serviceNo ) ; query . setParameter ( "serviceNo"

Scala language implementation of Selection Sort

Introduction Selection sort is the simplest sorting algorithm in terms of implementation. Let's consider we have a list of elements i.e. {3, 9, 0, 5, 4 } a) Selection sort maintains two sublists, one sorted and initially empty and second unsorted sublist i.e. [ {}, {3, 9 , 0, 5 ,4 }] b) It searches for the minimum element (for ascending sort) OR for a maximum element( for descending sort) in the unsorted list in each step. Step 1 [ {0 }, {9,3,5,4}] Minimum element = 0 , swapped with 3 Step 2 Minimum element = 3 , swapped with 9 [{0,3) , {9,5,4} ] Step 3 Minimum element = 4 , swapped with 9 [{0,3,4} , {5,9}] Step 4 Minimum element = 5 , swapped with itself [{0,3,4,5}, {9}] Step 5 Minimum element = 9 , swapped with itself [{0,3,4,5,9}, {}] Worst Complexity: O(n*n) Best Complexity   : O(n * n) Implementation package main.scala object SelectionSort { val array = Array(0, 5, 2, 6, 3, 1) def main(args: Array[String]) { print(&quo

Java Example of Selection Sort

Introduction Selection sort is the simplest sorting algorithm in terms of implementation. Let's consider we have a list of elements i.e. {3, 9, 0, 5, 4 } a) Selection sort maintains two sublists, one sorted and initially empty and second unsorted sublist i.e. [ {}, {3, 9 , 0, 5 ,4 }] b) It searches for the minimum element (for ascending sort) OR for a maximum element( for descending sort) in the unsorted list in each step. Step 1 [ {0 }, {9,3,5,4}] Minimum element = 0 , swapped with 3 Step 2 Minimum element = 3 , swapped with 9 [{0,3) , {9,5,4} ] Step 3 Minimum element = 4 , swapped with 9 [{0,3,4} , {5,9}] Step 4 Minimum element = 5 , swapped with itself [{0,3,4,5}, {9}] Step 5 Minimum element = 9 , swapped with itself [{0,3,4,5,9}, {}] Worst Complexity: O(n*n) Best Complexity   : O(n * n) Imperative style implementation using Java 7 public class SelectionSortExample { private static int array[] = {3,9,0,5,4}; public static void mai

Scala Implementation of Insertion Sort

Introduction Insertion sort is the best sorting algorithm for small-sized list of elements as compared to selection sort and  bubble sort . This sorting algorithm always maintains a sorted sublist within an iteration i.e. it finds the correct position of a single element at a time and inserts it in its correct position within the currently sorted sublist. Worst Complexity     : O(n*n) Best Complexity        : O(n) Average Complexity : O(n*n) Implementation package main.scala object InsertionSort {   val array = Array(0, 5, 2, 6, 3, 1)   def main(args: Array[String]) {     print("Unsorted List ")     println(array.toList)     print("Asceding sorted List ")     insertionSortAscending;     println(array.toList)     insertionSortDescending     print("Desceding sorted List ")     println(array.toList)   }   def insertionSortAscending { //first element is considered as sorted sublist     for (outer <- 1 until array.length) {

Java code of Insertion sort

Introduction Insertion sort is the best sorting algorithm for small-sized list of elements as compared to selection sort and bubble sort . This sorting algorithm always maintains a sorted sublist within an iteration i.e. it finds the correct position of a single element at a time and inserts it in its correct position within the currently sorted sublist. Worst Complexity    : O(n*n) Best Complexity        : O(n) Average Complexity : O(n*n) Imperative style using Java 7 public class InsertionSortExample { private static int array[] = {0,5,2,6,3,1,-9}; public static void main(String[] args) { insertionSortAscending(); System.out.println("Ascending Sorted List"); for(int value : array) { System.out.print(value + " "); } insertionSortDescending(); System.out.println("\nDescending Sorted List"); for(int value : array) { System.out.print(value + " "); } } private static void insertionSortAscending() {