Showing posts with label java collection tutorial. Show all posts
Showing posts with label java collection tutorial. Show all posts

Monday, 8 August 2016

How to Iterate through ConcurrentHashMap and print all keys and values in Java

Suppose you have a ConcurrentHashMap of String and Integer and you want to print all keys and values, how do you that? This is a common, day to day programming task for Java programmer and there are many ways to do it. The Map interface provides several view methods e.g. keySet(), values(), and entrySet() to retrieve all keys, values, and all key and value pairs as entries. You can use respective methods to print all keys, all values, or all key values pairs. For printing, you also have multiple choice e.g. you can either use enhanced for loop or Iterator, though later also provide you the facility to remove key value pairs while printing if needed. Though you should remember that these views are backed by Map, so when you remove a key-value pair from entry set it will also be removed by the ConcurrentHashMap.
Read more »

Saturday, 21 May 2016

What is difference between Synchronized and Concurrent Collections in Java?

Synchronized vs Concurrent Collections
Though both Synchronized and Concurrent Collection classes provide thread-safety, the differences between them comes  in performance, scalability and how they achieve thread-safety. Synchronized collections like synchronized HashMap, Hashtable, HashSet, Vector, and synchronized ArrayList are much slower than their concurrent counterparts e.g. ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteHashSet. Main reason for this slowness is locking; synchronized collections locks the whole collection e.g. whole Map or List while concurrent collection never locks the whole Map or List. They achieve thread safety by using advanced and sophisticated techniques like lock stripping. For example, the ConcurrentHashMap divides the whole map into several segments and locks only the relevant segments, which allows multiple threads to access other segments of same ConcurrentHashMap without locking.
Read more »

Friday, 18 March 2016

How to Reverse an ArrayList in Java using Recursion - Example Tutorial

If you ever need to reverse a List in Java e.g. ArrayList or LinkedList, you should always use the Collections.reverse() method. It's safe and tested and probably perform better than the first version of the method you write to reverse an ArrayList in Java. It's also one of the recommended best practice to prefer library method instead of writing your own, as advised by great Joshua Bloch in Effective Java. There are so many benefits of using library method e.g it was written by experts, thoroughly and open source tested and more actively maintained. Anyway, if you have been asked to write a function to reverse a List using recursion in Java, may be as part of your homework, assignment or during an interview, then you are in the right place. In this tutorial, I'll show you how to reverse an ArrayList of String using recursion. You can use this technique to reverse any type of List e.g. List of Integer, List of String or List of your own custom objects.
Read more »

Sunday, 6 March 2016

How to convert an Array to HashSet in Java - Example Tutorial

The array was there in Java before the Collection framework makes its entry in JDK 1.4, hence, you will find several legacy code, which accepts array than the Collection or Set. Due to this, we often need to convert an array to different types of collection e.g. List or Set. Earlier, I have told you the trick to convert an array to list and today I'll teach you how to convert an array to HashSet by using the same technique. The concept you need to know is that Collection provides a copy constructor i.e. you can pass a collection to create another collection. We'll leverage the same fact and to create an HashSet, we'll pass an ArrayList. Since you can use Arrays.asList() to convert an array to ArrayList, converting an array to HashSet is just two step job, first convert an array to a list and then convert a list to set.
Read more »

Friday, 22 January 2016

9 difference between Array vs ArrayList in Java

Both array and ArrayList are two important data structure in Java and frequently used in Java programs. Even though ArrayList is internally backed by an array, knowing the difference between an array and an ArrayList in Java is critical for becoming a good Java developer. If you know the similarity and differences, you can judiciously decide when to use an array over an AraryList or vice-versa. In this article, I'll help you understand the difference between ArrayList and array in Java. If you are coming from C or C++ background then you already know that array is one of the most useful data structure in the programming world. It offers O(1) performance for index-based search and one of the fundamental way to store data.
Read more »

Wednesday, 20 January 2016

How to declare and initialize a List (ArrayList and LinkedList) with values in Java

Initializing a list while declaring is very convenient for quick use, but unfortunately, Java doesn't provide any programming constructs e.g. collection literals, but there is a trick which allows you to declare and initialize a List at the same time. This trick is also known as initializing List with values. If you have been using Java programming language for quite some time then you must be familiar with syntax of array in Java and how to initialize an array in the same line while declaring it as shown below:

String[] oldValues = new String[] {"list" , "set" , "map"};

or even shorter :

String[] values = {"abc","bcd", "def"};

Similarly, we can also create List  and initialize it at the same line, popularly known as initializing List in one line example. Arrays.asList() is used for that purpose which returns a fixed size List backed by Array. By the way don’t confuse between Immutable or read only List which doesn’t allow any modification operation including set(index) which is permitted in fixed length List.Here is an example of creating and initializing List in one line:
Read more »

Tuesday, 19 January 2016

3 ways to loop over Set or HashSet in Java? Examples

Since Set interface or HashSet class doesn't provide a get() method to retrieve elements, the only way to take out elements from a Set is to iterate over it by using Iterator, or loop over Set using advanced for loop of Java 5. You can get the iterator by calling the iterator() method of Set interface. This method returns an iterator over the elements in the sets but they are returned in no particular order, as Set doesn't guarantee any order. Though individual Set implementations e.g. LinkedHashSet or TreeSet can impose ordering and in such iterator will return elements on that order. You can only traverse in one direction using iterator i.e. from first to last elements, there is no backward traversing allowed as was the case with List interface and ListIterator. Similarly, if you use advanced for loop, then also you can traverse in only one direction.
Read more »

Thursday, 7 January 2016

How does Java HashMap or LinkedHahsMap handles collisions?

Prior to Java 8, HashMap and all other hash table based Map implementation classes in Java handle collision by chaining, i.e. they use linked list to store map entries which ended in the same bucket due to a collision. If a key end up in same bucket location where an entry is already stored then this entry is just added at the head of the linked list there. In the worst case this degrades the performance of the get() method of HashMap to O(n) from O(1). In order to address this issue in the case of frequent HashMap collisions, Java8 has started using a balanced tree instead of linked list for storing collided entries. This also means that in the worst case you will get a performance boost from O(n) to O(log n).
Read more »

Wednesday, 6 January 2016

10 Examples of using ArrayList in Java - Tutorial

ArrayList in Java is most frequently used collection class after HashMap in Java. Java ArrayList represents an automatic re-sizeable array and used in place of the array. Since we can not modify the size of an array after creating it, we prefer to use ArrayList in Java which re-size itself automatically once it gets full. ArrayList in Java implements List interface and allow null. Java ArrayList also maintains insertion order of elements and allows duplicates opposite to any Set implementation which doesn't allow duplicates. ArrayList supports both Iterator and ListIterator for iteration but it’s recommended to use ListIterator as it allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the Iterator's current position in the list. But while using ListIterator you need to be little careful because ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). In this Java ArrayList tutorial, we will see how to create Java ArrayList and perform various operations on Java ArrayList. This collection class is also favorited on many core Java interviews with questions like Difference between ArrayList and Vector  or LinkedList vs ArrayList.
Read more »