Showing posts with label Collection Framework. Show all posts
Showing posts with label Collection Framework. Show all posts

Tuesday, March 27, 2018

Convert HashMap To ArrayList


1. a) Convert HashMap Keys Into ArrayList :

             We should use keySet() method of HashMap which will returns the Set containing all keys of the HashMap. After that, we should pass those while creating ArrayList.


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class HelloWorld{

     public static void main(String []args){
        //Creating a HashMap object
         
HashMap<String, String> map = new HashMap<String, String>();
map.put("1", "One");
map.put("2", "Two");
map.put("3", "Three");
map.put("4", "Four");
 
//Getting Set of keys from HashMap
         
Set<String> keySet = map.keySet();
         
//Creating an ArrayList of keys by passing the keySet
         
ArrayList<String> listOfKeys = new ArrayList<String>(keySet);
System.out.println("output is :" + listOfKeys);
     }
}

output is : [1, 2, 3, 4]


b) Convert HashMap Values Into ArrayList :

           We should use values() method of HashMap which will returns all values of the HashMap. After that, we should use this to create the ArrayList. let see an example below.


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class HelloWorld{

     public static void main(String []args){

//Creating a HashMap object
         
HashMap<String, String> map = new HashMap<String, String>();
 
map.put("1", "One");
map.put("2", "Two");
map.put("3", "Three");
map.put("4", "Four");
map.put("5", "Five");
//Getting Collection of values from HashMap
         
Collection<String> values = map.values();
         
//Creating an ArrayList of values
         
ArrayList<String> listOfValues = new ArrayList<String>(values);

System.out.println("output is " + listOfValues);
     }
}

output is : [One, Two, Three, Four, Five]



c) Convert HashMap Key-Value Pairs into ArrayList :

          We should use entrySet() method of HashMap which will returns the Set of Entry<K, V> objects where each Entry object represents one key-value pair. After that, We should pass this Set to ArrayList. let see below an example.


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class HelloWorld{

     public static void main(String []args){

HashMap<String, String> map = new HashMap<String, String>();

map.put("1", "One");
map.put("2", "Two");
map.put("3", "Three");
map.put("4", "Four");
map.put("5", "Five");

//Getting the Set of entries
         
Set<Entry<String, String>> entrySet = map.entrySet();
         
//Creating an ArrayList Of Entry objects
         
ArrayList<Entry<String, String>> listOfEntry = new ArrayList<Entry<String,String>>(entrySet);

System.out.println("output is " + listOfEntry);
     }
}

output is : [1=One, 2=Two, 3=Three, 4=Four, 5=Five]






Saturday, March 24, 2018

Some ways to iterate set

Below are some of the ways to iterate set in java. However still lot of other ways to do the same. But these are the basic you can use at any time easily.

Let see with an example.

1. Using Iterator
2. An  enhanced for loop
3. An enhanced for loop with java8

1. Using an Iterator


import java.util.HashSet;
import java.util.Iterator;

public class IterateHashSet{ 
  public static void main(String[] args) {
     // Create a HashSet
     HashSet<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("One");
     hset.add("Two");
     hset.add("Three");
     hset.add("Four");
     hset.add("Five");
 
     Iterator<String> it = hset.iterator();
     while(it.hasNext()){
        System.out.println(it.next());
     }
  }
}

Output:
Five
One
Four
Two
Three

Note: No ordered here.- Check output carefully.

2. An enhanced for loop


import java.util.HashSet;
import java.util.Set;

public class IterateHashSet{ 
  public static void main(String[] args) {
     // Create a HashSet
     Set<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("First");
     hset.add("Second");
     hset.add("Third");
     hset.add("Fourth");
     hset.add("Fifth");
 
     for (String temp : hset) {
        System.out.println(temp);
     }
  }
}

Output:

Second
Third
First
Fourth
Fifth



3. An enhanced for loop with java8


import java.util.HashSet;
import java.util.Set;

public class IterateHashSet{ 
  public static void main(String[] args) {
     // Create a HashSet
     Set<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("Test");
     hset.add("Second");
     hset.add("Third");
     hset.add("Fourth");
     hset.add("Fifth");
 
     hset.forEach(System.out::println);
  }
}

Output:

Second
Test
Third
Fourth
Fifth







Tuesday, May 3, 2016

How to avoid concurrent modification exception in java with Array List

There are some possible ways to avoid concurrent modification exception in java. we can see some possibility ways with example code.

Example I 

If you will try to remove an elements from an array list like below you will get concurrent exception. 
Code below.
for (String str : yourArrayList) {
        if (condition) {
            yourArrayList.remove(str);
        }
}

Solution for the above code:

You should use Iterator and its remove() method to do this. You should not use directly remove() method of array list.

Iterator<String> it = yourArrayList.iterator();

while (it.hasNext()) {
    String str = it.next();

    if (condition)
        it.remove();
}

Example II

 
Suppose if you are not interested to use iterator here, you can choose another option. Means, you should use another array list , which needs to add all of your removable objects. Code below.
ArrayList toRemoveElements = new ArrayList();
for (String str : yourArrayList) {
    if (condition) {
        toRemoveElements.add(str);
    }
}
yourArrayList.removeAll(toRemoveElements);


Example III

There is a third option you can use CopyOnWriteArrayList. Code below.
List<String> yourList = new CopyOnWriteArrayList<String>();
    yourList.add("A");
    yourList.add("B");

    for( String str : yourList )
    {
      if( condition )
      {
        yourList.remove( new String("B" ) );
      }
    }

Saturday, April 9, 2016

Concurrent Hash map with example

Generally If you are modify map object during run time, you will get exception as concurrent modification exception. To avoid this java brings a good concept called concurrent hash map from java 1.5. It is placed inside java.util.concurrent package.

Let start with a simple example and we can move depth.

package com.test.javahit;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
public class Fruits {
 
    public static void main(String[] args) {
 
        //Declaring ConcurrentHashMap
        Map map = new ConcurrentHashMap();
        map.put("1", "1");
        map.put("2", "2");
        map.put("3", "3");
        map.put("4", "4");
        map.put("5", "5");
        map.put("6", "6");

        System.out.println("ConcurrentHashMap before using iterator: "+map);
        Iterator it = map.keySet().iterator();
        
        while(it.hasNext()){
            String key = (String) it.next();
            if(key.equals("3")) map.put("newKey", "newValue");
        }
        System.out.println("ConcurrentHashMap after using iterator: "+map);
 
        //Declaring HashMap
        map = new HashMap();
        map.put("1", "1");
        map.put("2", "2");
        map.put("3", "3");
        map.put("4", "4");
        map.put("5", "5");
        map.put("6", "6");
        System.out.println("HashMap before iterator: "+map);
        Iterator iterator1 = map.keySet().iterator();
 
        while(iterator1.hasNext()){
            String key = (String) iterator1.next();
            if(key.equals("3")) map.put("new", "newValue");
        }
        System.out.println("HashMap after using iterator: "+map);
    }
 
}

Now just run the program and check the output.
ConcurrentHashMap before using iterator: {1=1, 5=5, 6=6, 3=3, 4=4, 2=2}
ConcurrentHashMap after using iterator: {1=1, newKey=newValue, 5=5, 6=6, 3=3, 4=4, 2=2}
HashMap before iterator: {3=3, 2=2, 1=1, 6=6, 5=5, 4=4}
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
 at java.util.HashMap$KeyIterator.next(HashMap.java:828)
at com.test.javahit.Fruits.main(Fruits.java:42)
From the above example, you could understand concurrent hashmap you can modify data while doing iteration and in hashMap can not.

We can see more, how its working. 

How to Initialize ?

It will be too good, if we will initialize with constructor parameters. For more understanding see below.

ConcurrentHashMap<String, Integer> concurrentHashMap = new ConcurrentHashMap<String, Integer>();

ConcurrentHashMap<String, Integer> concurrentHashMap = new ConcurrentHashMap<String, Integer>(16, 0.9f, 1);

Above two codes are just declaring the concurrent Hash Map. But Second declartion approach is good compared to first one. The reason behind is,

syntax for initializing constructor with concurrent Hash Map

ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel)

1. initialCapacity - capacity level size
2. loadFactor - Capacity level crossed means, how to add more capacity size
3. concurrencyLevel - Simply we can say thread level

As we all have good idea about first two points , but 3rd one concurrency level is just different. 16 number of concurrent threads can play with concurrent hash map. Before you set concurrency level, better to analyze more with your application. Since it will play huge performance.

Internally concurrent hash map will be divided into 16 number of participation and will assign each thread to one partition. It will maintain thread safety.  so that it will not throw any concurrent exception.

Points to Remember

1. Always use this when your project need huge concurrency level.
2. No need to synchronize separately. 
3. It performance will be good compared to synchronized hash map and hast table.
4. It wont allow both null key and null value.
5. It will lock particular portion of map only while doing update operation.

Thursday, April 7, 2016

How Hashset works internally in java ?

Set and HashSet

Set in an interface , it does not allow duplicates. It can allow null value at only one time. 

Hashset implements Set Interface and It is not synchronized, so its not thread safe. It stores the object in random order. Hashset is much faster than TreeSet.

Hashset Example

HashSet set = new HashSet();
     set.add("test");
     set.add("test1");
     set.add(null);
     System.out.println("Values are" + set);

Output: Values are[null, test1, test]


To add the elements into Hashset, which is using HashMap internally
public class HashSet 
 extends AbstractSet
 implements Set, Cloneable, java.io.Serializable

 private transient HashMap<E, Object> map;

 // Dummy value to associate with an Object in the backing Map

 private static final Object PRESENT = new Object();

 public HashSet() {
    map = new HashMap<>();
 }

 public boolean add(E e) {
     return map.put(e, PRESENT)==null;
    }
add(E e) method will be called after you add the element into set. If map.put(key,value) will return null, then condition will become true. Means, map.put(e,PRESENT) will return null (null ==null so TRUE). So element will be added.

Like same, If map.put(key,value) return old value of key, then condition will become false. Means, map.put(e,PRESENT)== null will return false (value!=null). So element will not be added. 

Here PRESENT is an dummy object reference and it will be used in map. 

Saturday, March 26, 2016

How HashMap works internally in java?

HashMap is working based on the concept of Hashing. Before moving into further, we should know the following concepts.
  • Hashing
  • Bucket
  • Collision
  • Entry
        Hashing - Assigning an unique code for all types of variable or object with the help of algorithm/function/formula.

       Bucket – Used to store Key Value pairs. It can have multiple key value pairs and this bucket will use LinkedList as an instance. Based on hash map length buckets will be created.

       Collision – If two key objects have same hashcode, then it is called collision.

       Entry – HashMap class have one inner class called Entry for storing your Key value pairs.


Structure of Entry class:

static class Entry implements Map.Entry
{
        final K key; //instance variable
        V value; // instance variable
        Entry next;
        final int hash;
        ...//More code goes here
}

Now let’s see how put(K key, V value) working

/**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with key, or
     *         null if there was no mapping for key.
     *         (A null return can also indicate that the map
     *         previously associated null with key.)
     */
    public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

  1.  First It will check whether given key is null or not. If specified Key is null then it will be stored at table [0]. Table [0] is nothing but, it is Bucket 0. It’s a rule; null should be always stored in index [0].
  2. Important point to remember, HashMap can allow only one null key.
  3.  Next if it is not null, hascode will be calculated for the key objects. This hascode will be useful to find the index of an array of your storing Entry object.(Key value)
  4.  Next indexFor (hash, table.length) will be executed and correct index integer value will be returned for storing Entry object.
  5.  There is a possibility two key object have same hashcode means Collison, and then it will be stored in the form of LinkedList.
  6. Suppose if no object is present in index, then it will directly put Entry object there.
  7. Suppose if any existing elements there, it will use next operation to find the place to put your Entry object. After finding it will put.
  8.  Next key.equals (k) will be executed to avoid adding duplicate keys. This method will check whether key object is equal or not. If it is equal (TRUE) it will replace your old Entry object with new Entry object (Current Entry object).

Now let’s see how (K key) get working


/**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * 
A return value of {@code null} does not necessarily
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        int hash = hash(key.hashCode());
        for (Entry e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
                return e.value;
        }
        return null;
    }

  1. First It will check whether given key is null or not. If specified Key is null then it will return value object of that key object. As it is null, value will be returned from Table[0](Bucket 0).
  2. If it is not null, hashcode will be calculated for the key object.
  3. Next it will identify where the exact index in table for the generated hashcode to get the Entry object with the help of indexFor (hash, table.length).
  4.  Once table [] index was found, it iterate the LinkedList and will check for key equality by using key.equals (k). If it will return TRUE, then value object of that Key will be returned. Otherwise, null will be returned.
Happy learning.

Thursday, February 27, 2014

Array List Tutorial

What is Array list?

Array list is a class that extends abstract list and implements the List interface. It will allow duplicates values.

Normal java array you have to set a size. But array list will support dynamic grow, that means it will be created with an initial size. After that if the size is exceeded, it will automatically increase the size. So Array Index out of bounds exception will not come.


The default value of array list size is 10. Now if you will add the 11th element half size will be increased half of its original size.

Remember, Array list is not synchronized. If you array list should be synchronized, use the below.

Collections.synchronizedList( new ArrayList());

It supports three constructors.

1.ArrayList()
2.ArrayList(Collection c)
3.ArrayList(int capacity)


Create Array List

You ca create an array list like below.


ArrayList<String> list = new ArrayList<String>(); //This Array List will Store only String objects

Adding values into array list


You can add the values into array list with the help of add method. 

list.add("java");
list.add("check");

Getting index of values


If you want to know the index of particular value, you have to pass that into the indexOf method. It will give the index. 

int index = list.indexOf("check");


Getting size of Array list values


If you want to know the size of the array list, you can use the size method.

int size = list.size();

Checking the array list is empty or not


If you want to check whether an array list is empty or not, use isEmpty method.
 
boolean result = list.isEmpty();

If the result value is true means, that's empty.Otherwise not.

Checking array list have an item


The conatains method will helpful to check array list have specified item or not.

boolean check = list.contains("java");

If the check value have true means, it have "java" value. Otherwise not.

Getting array list values through loop

With for loop you can get all values of array list.


for (String data: list) {
    System.out.println("The values are " + data);  
}

Removing an element from array list

To remove the specified object from list, you can use remove method.


list.remove("java");


Copying the data with ArrayList


addAll method will helpful for adding all list into another list.

ArrayList<String> listNew = new ArrayList<String>();
listNew.addAll(list);

Iterator and List Iterator with array list


Already we have seen, we can use enhanced for loop to get list values. Now you can use iterator and list Iterator to get values. See the below,

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

//Iterate with List Iterator

ListIterator listItr = list.listIterator();
while(listItr.hasNext()){
System.out.println(itr.next());
}

Simple array list example

package com.javahit.example;

import java.util.ArrayList;

public class JavaHitArrayList {

    public static void main(String[] args){

    //Creating arraylist... See I didn't mention any size
       
        ArrayList<String> al = new ArrayList<String>();
        //adding elements to the ArrayList
        al.add("one");
        al.add("two");
        al.add("three");
        al.add("four");
        System.out.println(al);

        //getting elements by index
        System.out.println("Index one value:"+al.get(1));


        //Checking the elements exist or not
        System.out.println("Checking existing value:"+al.contains("two"));

        //to add elements at index
        al.add(2,"PLAY");
       

        System.out.println("Checking array list empty "+al.isEmpty());
        System.out.println("Getting index value of two "+al.indexOf("two"));
        System.out.println("Arraylist size is: "+al.size());

        System.out.println(al);    
     }
}