Friday, 27 September 2013

PriorityBlockingQueue in Java

PriorityBlockingQueue in java

In our last tutorial we have see about PriorityQueue and how its used in Java with simple example. In this tutorial we will see about PriorityBlockingQueue and it works and also the difference between PriorityQueue and PriorityBlockingQueue. 
  • PriorityBlockingQueue uses same unbounded blocking queue that uses the same ordering rules as PriorityQueue and supplies blocking retrieval operations. 
  • PriorityBlockingQueue does not allow null values to be added.
  • PriorityBlockingQueue also uses natural sorting order and will not permit non-comparable objects to be insert which will result in ClassCastException exception.
  • PriorityBlockingQueue uses methods as same as PriorityQueue class except drainTo() and remainingCapacity() methods. 
  • drainTo(Collection<? super E> c) method used remove all available elements from the queue and adds them to the given collection.
  • drainTo(Collection<? super E> c, int maxElements) method used to remove at most the given number of available elements from the queue and adds them to the given collection.
  • remainingCapacity() method used to return Integer.MAX_VALUE because a PriorityBlockingQueue is not capacity constrained.
  • Method iterator() is not guaranteed to traverse the elements of PriorityBlockingQueue in any particular order. We can see this in below example. 

Difference Between PriorityBlockingQueue and PriorityQueue:
  • PriorityQueue is not thread safe, where as PriorityBlockingQueue is thread safe. 
  • PriorityBlockingQueue introduced in JDK 5 which added with concurrent package. 

Now lets see simple example for PriorityBlockingQueue and how its working under multi-threading.



import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.PriorityBlockingQueue;

public class PriorityBlockingQueueTest {
 
 PriorityBlockingQueue<String> priBlockQ = new PriorityBlockingQueue<String>();
 
 public PriorityBlockingQueueTest(){
  priBlockQ.add("300");
  priBlockQ.add("400");
  priBlockQ.add("100");
  priBlockQ.add("500");
  priBlockQ.add("200");  
 }
 
 public void performTask() {
  // traversing order not guaranteed
  System.out.println("\nQueue iterator() : ");
  Iterator<String> itr = priBlockQ.iterator();
  while (itr.hasNext()) {
   String string = (String) itr.next();
   System.out.print(string+", ");
  }
  
  System.out.println("\n\nList iterator() : ");
  List<String> list = new ArrayList<String>();
  priBlockQ.drainTo(list);
  itr = list.iterator();
  while (itr.hasNext()) {
   String string = (String) itr.next();
   System.out.print(string+", ");
  }
  
  System.out.println("\n\ncontains() : "+priBlockQ.contains("400"));
  System.out.println("\nremainingCapacity() : "+priBlockQ.remainingCapacity());
 }
 
 public static void main(String[] args) {
  new PriorityBlockingQueueTest().performTask();
 }
}


OUTPUT:


Queue iterator() : 
100, 200, 300, 500, 400, 

List iterator() : 
100, 200, 300, 400, 500, 

contains() : false

remainingCapacity() : 2147483647








read more.. "PriorityBlockingQueue in Java"

Wednesday, 25 September 2013

PriorityQueue in Java

PriorityQueue in Java

PriorityQueue is unbounded priority queue based on priority heap. 
  • Basically PriorityQueue are ordered according to natural ordering or by a Comparator provided at queue construction time, depending on which constructor is used. 
  • Another important that PriorityQueue won't take null value as input. 
  • Since PriorityQueue reply on natural ordering it won't take non-comparable object as input which will throw ClassCastException
  • Internally memory size will be managed automatically as and when elements added to the PriorityQueue.
  • By using Iterator interface its not guaranteed to traverse the elements of the PriorityQueue in any particular order. For ordered traversal need to use Arrays.sort(pq.toArray()). 
  • By implementation PriorityQueue is not synchronized and non-thread safe. Suppose if we need synchronized/thread-safe Queue then we need to go for PriorityBlockingQueue class instead of PriorityQueue.

Lets see list of constructors and methods in PriorityQueue class.

Constructors:

PriorityQueue()
          Default constructor which orders the elements in natural ordering.

PriorityQueue(Collection<? extends E> c)
          PriorityQueue will be created containing the elements in the specified collection.
 
PriorityQueue(int initialCapacity)
 PriorityQueue will be created with the initial size specified and orders its elements according to their natural ordering.

PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
 PriorityQueue will be created with the initial size specified and orders its elements according to the specified comparator

PriorityQueue(PriorityQueue<? extends E> c)
          PriorityQueue will be created with containing the elements in the specified priority queue.

PriorityQueue(SortedSet<? extends E> c)
          PriorityQueue will be created with containing the elements in the specified sorted set.


Methods:

boolean add(E e) 
Inserts the Element into PriorityQueue.

void clear()
Removes all elements from PriorityQueue.

Comparator<? super E> comparator()
Return Comparator used to order the elements in queue, or returns null if its ordered the queue in natural ordering. 

boolean contains(Object o) 
Return true if particular Object present in the queue else false.

Iterator<E> iterator() 
Used to iterate over the elements in the queue.

boolean offer(E e) 
Its same as add() method inserts the Elements into PriorityQueue.

Element peek()
Retrieves the Element from the head of queue else return null if queue is empty.

Element poll()
Retrieves and removes the Element from the head of queue else return null if queue is empty.

boolean remove() 
Retrieves and removes head of this queue.

boolean remove(Object o) 
Removes given Object from the queue if its present in the queue.

int size()
Returns the queue size. 

Object[] toArray()
Returns Object array containing all of the elements in this queue.

 <T> T[] toArray(T[] a)
Returns an array containing all of the elements in this queue; the run-time type of the returned array is that of the specified array and returned array elements are in no particular order.



Now lets see simple program using PriorityQueue class


import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;

public class PriorityQueueTest {

 public static void main(String[] args) {
  
  Queue<String> pq = new PriorityQueue<String>();
  
  pq.add("java");
  pq.add("servlet");
  pq.add("hibernate");
  
  pq.offer(".net");
  pq.offer("c");
  pq.offer("Pascal");
  
  System.out.println("\nPriorityQueue size() : "+pq.size());
  
  System.out.println("\nPriorityQueue peek() : "+pq.peek());
  
  System.out.println("\nIerating Queue Elements : ");
  Iterator<String> itr = pq.iterator();
  while (itr.hasNext()) {
   String string = (String) itr.next();
   System.out.print(string+", ");
  }
  
  System.out.println("\n\nPriorityQueue poll() : "+pq.poll());
  
  System.out.println("\nPriorityQueue size() : "+pq.size());
  
  System.out.println("\nPriorityQueue remove() : "+pq.remove());
  
  System.out.println("\nPriorityQueue remove(\".net\") : "+pq.remove(".net"));
  
  System.out.println("\nPriorityQueue contains() : "+pq.contains("java"));
  
  System.out.println("\nPriorityQueue toArray() : ");
  Object[] array = pq.toArray();
  for (Object object : array) {
   System.out.print(object.toString()+", ");
  }
 }
}


OUTPUT:


PriorityQueue size() : 6

PriorityQueue peek() : .net

Ierating Queue Elements : 
.net, c, Pascal, servlet, hibernate, java, 

PriorityQueue poll() : .net

PriorityQueue size() : 5

PriorityQueue remove() : Pascal

PriorityQueue remove(".net") : false

PriorityQueue contains() : true

PriorityQueue toArray() : 
c, hibernate, java, servlet, 








read more.. "PriorityQueue in Java"

Tuesday, 24 September 2013

Reverse LinkedList

Reverse Linkedlist using java code

This is one of the interview question which asked in recent interview like need to create a LinkedList and need to reverse those values in same linkedList without using addition list. We can make use of List implementation class LinkedList to achieve this. There are couple of ways we can achieve this in java by using Collection utility function reverse() and without reverse() function also. 
Lets see both the implementation in below examples. First lets see how to reverse LinkedList by using reverse() function. 


import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class LinkedListReverse {

 public static void main(String[] args) {
  
  List<Integer> list = new LinkedList<Integer>();
  list.add(3);
  list.add(6);
  list.add(7);
  list.add(0);
  list.add(1);
  list.add(4);
  list.add(9);
  list.add(5);
  
  System.out.println("Before Reverse : "+list.toString());
  
  Collections.reverse(list);
  
  System.out.println("After Reverse : "+list.toString());  
 }
}

OUTPUT:


Before Reverse : [3, 6, 7, 0, 1, 4, 9, 5]
After Reverse : [5, 9, 4, 1, 0, 7, 6, 3]

Next we will see how to reverse linkedlist without using reverse() function.


import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class LinkedListReverse {

 public static void main(String[] args) {
  
  List<Integer> list = new LinkedList<Integer>();
  list.add(3);
  list.add(6);
  list.add(7);
  list.add(0);
  list.add(1);
  list.add(4);
  list.add(9);
  list.add(5);
  
  System.out.println("Before Reverse : "+list.toString());
  
  ListIterator<Integer> itrFirst = list.listIterator();
  ListIterator<Integer> itrLast = list.listIterator();
  
  while (itrLast.hasNext()) {
   itrLast.next();   
  }
  
  for(int i = (list.size()/2)-1;itrFirst.hasNext() && itrLast.hasPrevious() && i>=0;i--){
   int first = itrFirst.next();
   int last = itrLast.previous();
   itrFirst.set(last);
   itrLast.set(first);
  }
  
  System.out.println("After Reverse : "+list.toString());  
 }
}

OUTPUT:


Before Reverse : [3, 6, 7, 0, 1, 4, 9, 5]
After Reverse : [5, 9, 4, 1, 0, 7, 6, 3]


read more.. "Reverse LinkedList"

Saturday, 21 September 2013

How to convert Java Properties file to XML file

Convert Java Properties file to XML file

In our earlier tutorial we have seen how to convert XML file to properties file. As a vice verse we will see how to convert XML file to java properties file in this tutorial. Lets consider there are property key with designation, city, state and country as same as previous tutorial example. Lets try to create same XML file using java properties file in below example code,


import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;

public class PropertyToXML {
 
 public static void main(String[] args) {
  try{
   Properties property = new Properties();
   property.setProperty("designation", "APAC Manager");
   property.setProperty("city", "Bangalore");
   property.setProperty("state", "Karnataka");
   property.setProperty("country", "India");
  
   // XML file path to save 
   OutputStream os = new FileOutputStream("D://propertiesToXML.xml");
    
   // Write properties into XML
      property.storeToXML (os, "Details");
      
  }catch (Exception e) {
   e.printStackTrace();
  }
 }
}


OUTPUT:





read more.. "How to convert Java Properties file to XML file "

How to convert XML file to Java Properties file

Convert XML file to Java Properties file
In one of our earlier tutorial we have seen how to use Properties class in Java to read property file. Basically property file hold key and corresponding  value part and by just loading those property files we can read application or project related properties which we have configured and also easy to modify those values. 
Same way by using Properties class we can convert XML file to Properties file and also vice-verse (Properties file to XML file). In this tutorial we will see about how to convert XML file to Java Properties file.

Input XML File:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">

<properties>
 <entry key="designation">Software Engineer</entry>
 <entry key="city">Bangalore</entry>
 <entry key="state">Karnataka</entry>
 <entry key="country">India</entry>
</properties>


Java Code to convert XML file to Java Properties file:


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

public class XMLToProperties {
 
 public static void main(String[] args) {
  try{
   Properties property = new Properties();
   InputStream is = new FileInputStream(new File("D://myproperties.xml"));
   property.loadFromXML(is);
   
   String designation = property.getProperty("designation");
   String city = property.getProperty("city");
   String state = property.getProperty("state");
   String country = property.getProperty("country");
   
   System.out.println(designation);
   System.out.println(city);
   System.out.println(state);
   System.out.println(country);
   
  }catch (Exception e) {
   e.printStackTrace();
  }
 } 
}


OUTPUT:


Software Engineer
Bangalore
Karnataka
India


In XML file <properties> and <entry> tag name must be same along with "key" attribute in entry tag which will be identified as key and value properties.  




read more.. "How to convert XML file to Java Properties file"

Friday, 20 September 2013

Character Frequency in String

Character Frequency in String

This is one of the easy interview programming question under 3 years experience. Lets assume given a lengthy string and asked you to find each character frequency. For example the given string is "hello java discover". In this string 'h'=1 , 'o'=2 etc., need to find each character occurred counts need to printed. 
We can achieve this by many ways like converting to character array and then manipulating each character or in looping count each character occurrence and store in any Collection object etc., In our below example we will use HashMap to store characters as key and their counts in value part.


import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class CharFreq {

 public static void main(String[] args) {

  String str = "hello javadiscover";

  Map<Character, Integer> map = new HashMap<Character, Integer>();

  for (int i = 0; i < str.length(); i++) {
   char ch = str.charAt(i);
   if (map.get(ch) != null) {
    map.put(ch, (map.get(ch) + 1));
   } else {
    map.put(ch, 1);
   }
  }

  Set<Character> set = map.keySet();
  for (Character character : set) {
   System.out.println(character + " : " + map.get(character));
  }
 }
}


OUTPUT:


  : 1 // space character 
d : 1
e : 2
c : 1
a : 2
o : 2
l : 2
j : 1
h : 1
i : 1
v : 2
s : 1
r : 1



read more.. "Character Frequency in String"

Array with Even and Odd numbers

Array with Even and Odd numbers

This is one of the interesting interview question which asked about integer array. Before going into direct question please refer to other tutorial about Java Array which we discussed earlier. 

There is an integer array with combination of Even and Odd numbers. Numbers are un-ordered and need to arrange all even numbers left and all odd numbers at right side with ascending order respectively ie., all even numbers at left side and all odd numbers at right should to sorted separately. For example if the input array is {4,6,1,5,8,3,2,7,9}, then output should be {2,4,6,8,1,3,5,7,9}
The constraints are 
  • Should not use any additional array
  • Should not use any collection API
Need to arrange and sort integers in same array. Lets see Java solution for this program by sorting and arranging integers.


public class EvenOddArray {

 public static void main(String[] args) {

  int[] array = new int[] {31, 30, 4, 6, 8, 3, 2, 7, 9, 12, 34, 11 };

  int evenPnt = 0;
  
  // Arranging Even and Odd numbers
  for (int i = 0; i < array.length; i++) {
   if (array[i] % 2 == 0) {
    swap(array, evenPnt, i);
    evenPnt++;
   }
  }
  
  // Sorting even numbers
  sort(array, 0, evenPnt);
  
  // Sorting Odd numbers 
  sort(array, evenPnt, array.length);

  for (int i : array) {
   System.out.print(i+", ");
  } 
 }

 public static void sort(int[] arr, int min, int max) {
  for (int i = min; i < (max - 1); i++) {
   for (int j = i + 1; j < max; j++) {
    if (arr[i] > arr[j]) {
     swap(arr, i, j);
    }
   }
  }
 }

 public static void swap(int[] arr, int i, int j) {
  int tmp = arr[i];
  arr[i] = arr[j];
  arr[j] = tmp;
 }
}


OUTPUT:


2, 4, 6, 8, 12, 30, 34, 3, 7, 9, 11, 31, 

read more.. "Array with Even and Odd numbers "