Thursday, 18 December 2014

Java Collection

Java Collection


ArrayList
……………….
import java.util.ArrayList;
class App
{
   public static void main(String args[])
   {
   ArrayList<Integer> number = new ArrayList<Integer>();
   number.add(12);
   number.add(112);
   number.add(312);
   number.add(65);
   number.add(132);
   System.out.println(number.get(2));
   System.out.println(number);
   number.remove(0);
   number.add(25);
   for(int i=0; i<number.size(); i++)
   System.out.println(number.get(i));
   number.remove(2);
   number.remove(number.size()-1);
   for(int i=0; i<number.size(); i++)
   System.out.println(number.get(i));
   }
 }
  Output
…………………..
312
[12, 112, 312, 65, 132]
112
312
65
132
25
112
312
132

LinkedList
……………..

import java.util.LinkedList;
class App
{
   public static void main(String args[])
   {
   LinkedList<Integer> number = new LinkedList<Integer>();
   number.add(12);
   number.add(112);
   number.add(312);
   number.add(65);
   number.add(132);
   System.out.println(number.get(2));
   System.out.println(number);
   number.remove(0);
   number.add(25);
   for(int i=0; i<number.size(); i++)
   System.out.println(number.get(i));
   number.remove(2);
   number.remove(number.size()-1);
   for(int i=0; i<number.size(); i++)
   System.out.println(number.get(i));
   }
 }
   Output
…………………..
312
[12, 112, 312, 65, 132]
112
312
65
132
25
112
312
132

ArrayList is fast in random access. If I want to get the 8th element then the 3rd element then the 7th and then the 2nd element, ArrayList will provide the best performance. LinkedList is slow in random access 

LinkedList is used when you modify the list a lot. If you'll add and remove elements to the List a lot of times, LinkedList should be used. ArrayList is slow in terms of additions and removal...


HashMap
HashMap is an object that stores both “key/value” as a pairs. In this article, we show you how to create a HashMap instance and iterates the HashMap data.
["mkyong","1000.00"] = ["key","value"]
In above, “mkyong” is the key , “1000.00″ is the value. By given a key “mkyong”, you can get the value “1000.00″.

  • The java HashMap class does not guarantee that the order will remain constant over time.
  • This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
  • The HashMap implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.


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

public class Number {
            public static void main(String[] args) {
                       
                                    Map mMap = new HashMap();
                                    mMap.put("PostgreSQL", "Free Open Source Enterprise Database");
                                    mMap.put("DB2", "Enterprise Database , It's expensive");
                                    mMap.put("Oracle", "Enterprise Database , It's expensive");
                                    mMap.put("MySQL", "Free Open SourceDatabase");
                        System.out.println(mMap);
                         
                                   
            }
}


Output
{PostgreSQL=Free Open Source Enterprise Database, MySQL=Free Open SourceDatabase, Oracle=Enterprise Database , It's expensive, DB2=Enterprise Database , It's expensive}

Set, Map, ArrayList, LinkedList

import java.util.*;
 
public class CollectionsDemo {
 
        public static void main(String[] args) {
               List a1 = new ArrayList();
               a1.add("Beginner");
               a1.add("Java");
               a1.add("tutorial");
               System.out.println(" ArrayList Elements");
               System.out.print("\t" + a1);
               List l1 = new LinkedList();
               l1.add("Beginner");
               l1.add("Java");
               l1.add("tutorial");
               System.out.println();
               System.out.println(" LinkedList Elements");
               System.out.print("\t" + l1);
               Set s1 = new HashSet(); // or new TreeSet() will order the elements;
               s1.add("Beginner");
               s1.add("Java");
               s1.add("Java");
               s1.add("tutorial");
               System.out.println();
               System.out.println(" Set Elements");
               System.out.print("\t" + s1);
               Map m1 = new HashMap(); // or new TreeMap() will order based on keys
               m1.put("Windows", "98");
               m1.put("Win", "XP");
               m1.put("Beginner", "Java");
               m1.put("Tutorial", "Site");
               System.out.println();
               System.out.println(" Map Elements");
               System.out.print("\t" + m1);
        }
}

Output
ArrayList Elements
            [Beginner, Java, tutorial]
 LinkedList Elements
            [Beginner, Java, tutorial]
 Set Elements
            [tutorial, Beginner, Java]
 Map Elements
            {Tutorial=Site, Windows=98, Win=XP, Beginner=Java}

ArrayList
………………..
  • A java ArrayList is used to store an “ordered” group of elements where duplicates are allowed.
  • Implements all optional list operations, and permits all elements, including null.
  • This class is similar to Vector, except that it is unsynchronized.
  • The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. ArrayList’s give great performance on get() and set() methods, but do not perform well on add() and remove() methods when compared to a LinkedList.
  • An ArrayList capacity is the size of the array used to store the elements in the list. As elements are added to an ArrayList, its capacity grows automatically. It is an Array based implementation where elements of the List can be accessed directly through get() method.
LinkedList
………………
  • A LinkedList is used to store an “ordered” group of elements where duplicates are allowed.
  • A LinkedList is based on a double linked list where elements of the List are typically accessed through add() and remove() methods.
HashSet
………………….
  • he HashSet class implements the Set interface.
  • It makes no guarantee that the order of elements will remain constant over time.
  • This class is not synchronized and permits a null element.
  • This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.
  • To prevent unsynchronized access to the Set: Set s = Collections.synchronizedSet(new HashSet(…));
Vector
………..
  • The Vector class implements a growable array of objects where the size of the vector can grow or shrink as needed dynamically.
  • Like an array, it contains components that can be accessed using an integer index.
  • An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.
Sorting arraylist:
import java.util.ArrayList;
import java.util.Collections;

class App
{
   public static void main(String args[])
   {
   ArrayList<String> number = new ArrayList<String>();
   number.add("abh");
   number.add("gdg");
   number.add("agh");
   number.add("pliy");
   number.add("eee");
  
   System.out.println(number);
   Collections.sort(number );
   System.out.println(number);
   }
 }

TreeSet directely gives output as sorting
import java.util.Set;
import java.util.TreeSet;
import java.util.Collections;

class App
{
   public static void main(String args[])
   {
   Set<String> number = new TreeSet<String>();
   number.add("abh");
   number.add("gdg");
   number.add("agh");
   number.add("pliy");
   number.add("eee");
  
   System.out.println(number);
 
   }
 }
Output
[abh, agh, eee, gdg, pliy]

How HashMap  works in Java
HashMap  works on principle of hashing, we have put() and get() method for storing and retrieving object form HashMap .When we pass an both key and value to put() method to store on HashMap , it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object. While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap  uses linked list in case of collision and object will be stored in next node of linked list.
Also HashMap  stores both key+value tuple in every node of linked list.

What will happen if two different HashMap  key objects have same hashcode?
Since hashcode is same, bucket location would be same and collision will occur in HashMap, Since HashMap use LinkedList to store object, this entry (object of Map.Entry comprise key and value )  will be stored in LinkedList. 

How to retrieve object value for same hashcode?
we will call keys.equals() method to identify correct node in LinkedList and return associated value object for that key in Java HashMap .

"What happens On HashMap in Java if the size of the HashMap  exceeds a given threshold defined by load factor ?".

Java HashMap re-size itself by creating a new bucket array of size twice of previous size of HashMap , and then start putting every old element into that new bucket array. This process is called rehashing because it also applies hash function to find new bucket location. 
"do you see any problem with resizing of HashMap  in Java" ,
 you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the Java HashMap and potentially looking for race condition on HashMap  in Java

So the answer is Yes there is potential race condition exists while resizing HashMap in Java, if two thread at the same time found that now HashMap needs resizing and they both try to resizing. on the process of resizing of HashMap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because java HashMap  doesn't append the new element at tail instead it append new element at head to avoid tail traversing. If race condition happens then you will end up with an infinite loop. Though this point you can potentially argue that what the hell makes you think to use HashMap  in multi-threaded environment to interviewer :)


Sorting ArrayList in Java – Code Example


Here is a complete code example of How to sort ArrayList in Java, In this Sorting we have used Comparable method ofString for sorting String on there natural order, You can also use Comparator in place of Comparable to sort String on any other order than natural ordering e.g. in reverse order by using Collections.reverseOrder() or in case insensitive order by using String.CASE_INSENSITIVE_COMPARATOR.

import java.util.ArrayList; 
import java.util.Collections; 

public class CollectionTest { 

    
    
public static void main(String args[]) { 
    
        
//Creating and populating ArrayList in Java for Sorting 
        ArrayList
<String> unsortedList = new ArrayList<String>(); 
        
        unsortedList.
add("Java"); 
        unsortedList.
add("C++"); 
        unsortedList.
add("J2EE"); 
        
        System.
err.println("unsorted ArrayList in Java : " + unsortedList); 
        
        
//Sorting ArrayList in ascending Order in Java 
        Collections.
sort(unsortedList); 
        System.
out.println("Sorted ArrayList in Java - Ascending order : " + unsortedList); 
        
        
//Sorting ArrayList in descending order in Java 
        Collections.
sort(unsortedList, Collections.reverseOrder()); 
        System.
err.println("Sorted ArrayList in Java - Descending order : " + unsortedList); 
    
} 
} 
Output: 
unsorted ArrayList in Java : 
[Java, C++, J2EE] 
Sorted ArrayList in Java - Ascending order : 
[C++, J2EE, Java] 
Sorted ArrayList in Java - Descending order : 
[Java, J2EE, C++]

Java HashMap Example 9: Sorting HashMap in Java
HashMap is an unsorted Map in Java, neither key or value is sorted. If you want to sort HashMap than you can sort it based upon key or value, see how to sort HashMap on keys and values for full code example.  Alternatively, you can use SortedMap in Java likeTreeMap. TreeMap has constructor which accepts Map and can create a Map sorted on natural order of key or any custom sorting order defined by Comparator. Only thing is key should be naturally comparable and there compareTo() method shouldn't throw exception. Just to remind there is no Collections.sort() method defined for Map is only for List and it’s implementation e.g.ArrayList or LinkedList. So any sorting for Map require SortedMap or custom code for sorting on either key or value. here is code example of sorting HashMap in Java by using TreeMap in natural order of keys:
map.put(21, "Twenty One");
map.put(31, "Thirty One");
map.put(41, "Thirty One");
 
System.out.println("Unsorted HashMap: " + map);
TreeMap sortedHashMap = new TreeMap(map);     
System.out.println("Sorted HashMap: " + sortedHashMap); 
 
Output:
Unsorted HashMap: {21=Twenty One, 41=Thirty One, 31=Thirty One}
Sorted HashMap: {21=Twenty One, 31=Thirty One, 41=Thirty One}

TreeSet vs TreeMap in Java
Now let's see some differences between TreeSet vs TreeMap in Java:

1) Major difference between TreeSet and TreeMap is that TreeSet implements Set interface while TreeMap implements Map interface in Java.

2) Second difference between TreeMap and TreeSet is the way they store objects. TreeSet stores only one object while TreeMap uses two objects called key and Value. Objects in TreeSet are sorted while keys in TreeMap remain in sorted Order.

3) Third difference between TreeSet and TreeMap is that, former implements NavigableSet while later implementsNavigableMap in Java.

4) Fourth difference is that duplicate objects are not allowed in TreeSet but duplicates values are allowed in TreeMap.

HashSet vs TreeSet in Java

Difference between HashSet vs TreeSet in JavaNow let's see couple of differences between HashSet vs TreeSet in Java. This is enough to decide whether you should use HashSet or TreeSet in a given scenario.

1) First major difference between HashSet and TreeSet is performance. HashSet is faster than TreeSet and should be preferred choice if sorting of element is not required.

2) Second difference between HashSet and TreeSet is that HashSet allows null object but TreeSet doesn't allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo() method to compare keys and compareTo() will throwjava.lang.NullPointerException as shown in below example :

HashSet<String> hashSet = new HashSet<String>(); 
hashSet.
add("Java"); 
hashSet.
add(null); 
        
TreeSet
<String> treeSet = new TreeSet<String>(); 
treeSet.
add("C++"); 
treeSet.
add(null); //Java.lang.NullPointerException 
Output: 
Exception in thread 
"main" java.lang.NullPointerException 
        at java.
util.TreeMap.put(TreeMap.java:541) 
        at java.
util.TreeSet.add(TreeSet.java:238) 
        at test.
CollectionTest.main(CollectionTest.java:27) 
Java Result: 
1


3) Another significant difference between HashSet and TreeSet is that , HashSet is backed by HashMap while TreeSet is backed by TreeMap in Java.

4) One more difference between HashSet and TreeSet which is worth remembering is that HashSet uses equals() method tocompare two object in Set and for detecting duplicates while TreeSet uses compareTo() method for same purpose. if equals() and compareTo() are not consistent, i.e. for two equal object equals should return true while compareTo() should return zero, than it will break contract of Set interface and will allow duplicates in Set implementations like TreeSet

5) Now most important difference between HashSet and TreeSet is ordering. HashSet doesn't guaranteed any order whileTreeSet maintains objects in Sorted order defined by either Comparable or Comparator method in Java.


How to Remove Duplicate Values From Java List/ArrayList?



import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

public class RemDupFromList {

    public static void main(String[] args)
    {
        List li = new ArrayList();

              li.add("one");
              li.add("two");
              li.add("three");
              li.add("one");//Duplicate
              li.add("one");//Duplicate

             // We have facility to pass a List into Set constructor and vice verse to cast      

                List li2 = new ArrayList(new HashSet(li)); //no order

             // List li2 = new ArrayList(new LinkedHashSet(li)); //If you need to preserve the order use 'LinkedHashSet'

             Iterator it= li2.iterator();
             while(it.hasNext())
             {
                 System.out.println(it.next());
             }

    }
}

Explanation
·         Take your normal List object
·         Pass that List li object to Set [Line number 22]  => So finally we have Set object in our hand, just pass this current Set object as argument to ArrayList, so we got new List object li2 without duplicate
·         But if you would like to preserve the order of data use LinkedHashSet rather HashSet

//Iterate  with the help of Iterator class (for list)
                System.out.println("Iterating with the help of Iterator class");
                Iterator iterator = arrJavaTechnologies.iterator();
                while(iterator.hasNext()){
                        System.out.println( iterator.next() );
                }


No comments:

Post a Comment