Showing posts with label Collections. Show all posts
Showing posts with label Collections. Show all posts

Sunday, 30 August 2015

Iterate over HashMap

Best way to Iterate over HashMap in Java

Here is the code example of Iterating over any Map class in Java e.g. Hashtable or LinkedHashMap. Though I have used HashMap for iteration purpose, you can apply same technique to other Map implementations. Since we are only using methods from java.uti.Map interface, solution is extensible to all kinds of Map in Java. We will use Java 1.5 foreach loop and Iterating over each Map.Entry object, which we get by calling Map.entrySet() method. Remember to use Generics, to avoid type casting. Use of Generics and foreach loop result in very concise and elegant code, as shown below.


for(Map.Entry<Integer, String> entry : map.entrySet()){
    System.out.printf("Key : %s and Value: %s %n", entry.getKey(), entry.getValue());
}

This code snippet is very handy for iterating HashMap, but has just one drawback, you can not remove entries without risking ConcurrentModificationException. In next section, we will see code using Iterator, which can help you for removal of entries from Map.



Removing Entries from Map in Java

One reason for iterating over Map is removing selected key value pairs from Map. This is a general Map requirement and holds true for any kind of Map e.g. HashMap, Hashtable, LinkedHashMap or even relatively new ConcurrentHashMap. When we use foreach loop, it internally translated into Iterator code, but without explicit handle to Iterator, we just can not remove entries during Iteration. If you do,  your Iterator may throw ConcurrentModificationException. To avoid this, we need to use explicit Iterator and while loop for traversal. We will still use entrySet() for performance reason, but we will use Iterator's remove() method for deleting entries from Map. Here code example  to remove key values from HashMap in Java:



  //code goes here
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
   Map.Entry<Integer, String> entry = iterator.next();
   System.out.printf("Key : %s and Value: %s %n", entry.getKey(), entry.getValue());
   iterator.remove(); // right way to remove entries from Map,
                      // avoids ConcurrentModificationException
}


You can see, we are using remove() method from Iterator and not from java.util.Map, which accepts a key object. This code is safe from ConcurrentModificationException.


Read more: http://java67.blogspot.com/2013/08/best-way-to-iterate-over-each-entry-in.html#ixzz3kIiWUMZU

Sorting ArryList in java

Sorting ArrayList in Java is not difficult, by using Collections.sort() method you can sort ArrayList in ascending and descending order in Java. Collections.sort() method optionally accept a Comparator and if provided it uses Comparator's compare method to compare Objects stored in Collection to compare with each other, in case of no explicit Comparator, Comparable interface's compareTo() method is used to compare objects from each other. If object's stored in ArrayList doesn't implements Comparable than they can not be sorted using Collections.sort() method in Java.


Sorting ArrayList in Java – Code Example

ArrayList Sorting Example in Java - Ascending Descending Order Code
Here is a complete code example of How to sort ArrayList in Java, In this Sorting we have used Comparable method of String for sorting String on their 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.

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);
    }
}

Iterator vs Enumerator

Between Enumeration and Iterator, Enumeration is older and its there from JDK1.0, while iterator was introduced later. Iterator can be used with ArrayList, HashSet and other collection classes.  Another similarity between Iterator and Enumeration in Java is that  functionality of Enumeration interface is duplicated by the Iterator interface.

Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as by using Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist.

Also Iterator is more secure and safe as compared to Enumeration because it  does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException. This is by far most important fact for me for deciding between Iterator vs Enumeration in Java.

In Summary both Enumeration and Iterator will give successive elements, but Iterator is new and improved version where method names are shorter, and has new method called remove. Here is a short comparison:

Enumeration
hasMoreElement()
nextElement()
N/A


Iterator
hasNext()
next()
remove()

So Enumeration is used when ever we want to make Collection objects as Read-only.

Monday, 10 August 2015

ArrayList vs LinkedList vs Vector

ArrayList, LinkedList, and Vector are all implementations of the List interface. Which of them is most efficient for adding and removing elements from the list? Explain your answer, including any other alternatives you may be aware of.
View the answer ?


Of the three, LinkedList is generally going to give you the best performance. Here’s why:

ArrayList and Vector each use an array to store the elements of the list. As a result, when an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is not needed, it is recommended to use ArrayList rather than Vector.

LinkedList, on the other hand, is implemented using a doubly linked list. As a result, an inserting or removing an element only requires updating the links that immediately precede and follow the element being inserted or removed.

However, it is worth noting that if performance is that critical, it’s better to just use an array and manage it yourself, or use one of the high performance 3rd party packages such as Trove or HPPC.

fail-fast vs fail-safe


The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not.

Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified (i.e., upon realizing that a member has been added, modified, or removed) and will throw a ConcurrentModificationException. Some examples include ArrayList, HashSet, and HashMap (most JDK1.4 collections are implemented to be fail-fast).

Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration. Examples would include iterators returned by ConcurrentHashMap or CopyOnWriteArrayList.

Examples:

public class FailFastExample
{
   
    public static void main(String[] args)
    {
        Map<String,String> premiumPhone = new HashMap<String,String>();
        premiumPhone.put("Apple", "iPhone");
        premiumPhone.put("HTC", "HTC one");
        premiumPhone.put("Samsung","S5");
       
        Iterator iterator = premiumPhone.keySet().iterator();
       
        while (iterator.hasNext())
        {
            System.out.println(premiumPhone.get(iterator.next()));
            premiumPhone.put("Sony", "Xperia Z");
        }
    }
}

public class FailSafeExample
{
    public static void main(String[] args)
    {
        ConcurrentHashMap<String,String> premiumPhone =
                               new ConcurrentHashMap<String,String>();
        premiumPhone.put("Apple", "iPhone");
        premiumPhone.put("HTC", "HTC one");
        premiumPhone.put("Samsung","S5");
       
        Iterator iterator = premiumPhone.keySet().iterator();
       
        while (iterator.hasNext())
        {
            System.out.println(premiumPhone.get(iterator.next()));
            premiumPhone.put("Sony", "Xperia Z");
        }
   
   }
 

}

Thursday, 23 July 2015

Collections utility class in Java Collections


Utility/Polymorphic methods in class Collections




ConcurrentHashMap vs HashMap

 1.  Thread-Safe & fail-safe

     ConcurrentHashMap is thread-safe that is the code can be accessed by single thread at a time .
     while HashMap is not thread-safe.

 2.  Synchronization Method :

    HashMap can be synchronized by using synchronizedMap(HashMap)  method.
    By using this method we get a HashMap object which is equivalent to the HashTable object .               So every modification is performed on Map is locked on Map object.


  •   ConcurrentHashMap synchronizes or locks on the certain portion of the Map. To optimize           the performance of ConcurrentHashMap , Map is divided into different partitions depending     upon the Concurrency level. So that we do not need to synchronize the whole Map Object.


3.  Null Key

     ConcurrentHashMap does not allow NULL values . So the key can not be null in                                        ConcurrentHashMap .While In HashMap there can only be one null key.

4.  Performance

     In multiple threaded environment HashMap is usually faster than ConcurrentHashMap as  
     only single thread can access the certain portion of the Map and thus reducing the performance.
     While in HashMap any number of threads can access the code at the same time.

Arraylist vs Vector


1.  Synchronization and Thread-Safe

Vector is  synchronized while ArrayList is not synchronized  . Synchronization and thread safe means at a time only one thread can access the code .In Vector class all the methods are synchronized .That's why the Vector object is already synchronized when it is created .

2.  Performance

Vector is slow as it is thread safe . In comparison ArrayList is fast as it is non synchronized . Thus     in ArrayList two or more threads  can access the code at the same time  , while Vector is limited to one thread at a time.

3. Automatic Increase in Capacity

A Vector defaults to doubling size of its array . While when you insert an element into the ArrayList ,      it increases
its Array size by 50%  .


By default ArrayList size is 10 . It checks whether it reaches the last  element then it will create the new array ,copy the new data of last array to new array ,then old array is garbage collected by the Java Virtual Machine (JVM) . 

4. Set Increment Size

ArrayList does not define the increment size . Vector defines the increment size .

You can find the following method in Vector Class

public synchronized void setSize(int i) { //some code  }

There is no setSize() method or any other method in ArrayList which can manually set the increment size.

5. Enumerator

Other than Hashtable ,Vector is the only other class which uses both Enumeration and Iterator.While ArrayList can only use Iterator for traversing an ArrayList .

6.  Introduction in Java 

java.util.Vector  class was there in java since the very first version of the java development kit (jdk).
java.util.ArrayList  was introduced in java version 1.2 , as part of Java Collections framework . In java version 1.2 , Vector class has been refactored to implement the List Interface .

TreeSet vs HashSet

Difference between HashSet and TreeSet

1. Ordering : HashSet stores the object in random order . There is no guarantee that the element we  inserted first in the HashSet  will be printed first in the output . For example  

Elements are sorted according to the natural ordering of its elements in TreeSet. If the objects can not
be sorted in natural order than use compareTo() method to sort the elements of TreeSet object .

2. Null value :   HashSet can store null object while TreeSet does not allow null object. If one try to store null object in TreeSet object , it will throw Null Pointer Exception.

3. Performance : HashSet take constant time performance for the basic operations like add, remove contains and  size.While TreeSet guarantees log(n) time cost for the basic operations (add,remove,contains).

4. Speed : HashSet is much faster than TreeSet,as performance time of HashSet is constant against the log time of TreeSet for most operations (add,remove ,contains and size) . Iteration performance of HashSet mainly depends on the load factor and initial capacity parameters.

5. Internal implementation :  As we have already discussed How hashset internally works in java thus, in one line HashSet are internally backed by hashmap. While TreeSet is backed by a  Navigable  TreeMap.

6. Functionality :    TreeSet is rich in functionality as compare to HashSet. Functions like pollFirst(),pollLast(),first(),last(),ceiling(),lower() etc. makes TreeSet easier to use than HashSet.

7. Comparison : HashSet uses equals() method for comparison in java while TreeSet uses compareTo() method for maintaining ordering .

To whom priority is given TreeSet comparator or Comparable.compareTo() .

Suppose there are elements in TreeSet which can be naturally sorted by the TreeSet , but we also added our own sorting method by implementing Comparable interface compareTo() method .
Then to whom priority is given.


Answer to the above question is that the Comparator passed into the TreeSet constructor has been given priority.
According to Oracle Java docs

public TreeSet(Comparator comparator)

Constructs a new, empty tree set, sorted according to the specified comparator.

   Parameters:
 
   comparator - the comparator that will be used to order this set. If null, the natural ordering of the elements will be used.




Similarities Between HashSet and TreeSet

1. Unique Elements :   Since HashSet and TreeSet both implements Set interface . Both are allowed to store only unique elements in their objects. Thus there can never be any duplicate elements inside the HashSet and TreeSet objects.

2. Not Thread Safe : HashSet and TreeSet both are not synchronized or not thread safe.HashSet and TreeSet, both implementations are not synchronized. If multiple threads access a hash set/ tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.

3. Clone() method copy technique:  Both HashSet and TreeSet uses shallow copy technique to create a clone of  their objects .

4. Fail-fast Iterators :  The iterators returned by this class's  method are fail-fast: if the set is modified at any time after the iterator is  created, in any way except through the iterator's own  remove method, the iterator will throw a  ConcurrentModificationException.  Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at   an undetermined time in the future.


When to prefer TreeSet over HashSet

1.  Sorted unique elements are required instead of unique elements.The sorted list given by TreeSet is always in ascending order.

2.   TreeSet has greater locality than HashSet.

If two entries  are near by in the order , then TreeSet places them near each other in data structure and hence in memory, while HashSet spreads the entries all over memory  regardless of the keys they are associated to.
   
As we know Data reads from the hard drive takes much more latency time than data read from the cache or memory. In case data needs to be read from hard drive than prefer TreeSet as it has greater locality than HashSet.

3. TreeSet uses Red- Black tree algorithm underneath to sort out the elements. When one need to perform read/write operations frequently , then TreeSet is a good choice.
 
Thats it for the difference between HashSet and TreeSet , if you have any doubts then please mention in the comments.

Wednesday, 22 July 2015

Java Collections









What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
  1. Collection extends Iterable
  2. An iterator is an object that enables t traverse through a collection and to remove elements from the collection selectively, if required.
  3. Set
  • Set is a Collection that cannot contain duplicate elements.
  • Set interface contains only methods from Collection.
  • Two Set instances are equal if they have same elements.
  • There are three Set implementations
      HashSet
  • Stores the elements in a hash table
  • Uses hashtable to store the elements.It extends AbstractSet class and implements Set interface.
  • Contains unique elements only.
      TreeSet – orders the elements based on their values

       List<String> li = new ArrayList<String>();
       TreeSet<String> myset = new TreeSet<String>(li);


  • Removing duplicates from array.

               String[] strArr = {"one","two","three","four","four","five"};
               List<String> tmpList = Arrays.asList(strArr);

               TreeSet<String> unique = new TreeSet<String>(tmpList);

      LinkedHashSet – orders the elements based on the order in which it is inserted
  • Bulk operations:
              If s1 and s2 are two sets:
              s1. containsAll(s2) – returns true if s2 is a subset of s1
              s1.addAll(s1) – transforms s1 into the union of s1 and s2
              s1.retainAll(s2) – transforms s1 into the intersection of s1 and s2
              s1.removeAll(s2) – transforms s1 into the set difference of s1 and s24


  1. Arrays,Collections are utility class available in java.util package.