Showing posts with label hashmap. Show all posts
Showing posts with label hashmap. Show all posts

Monday, May 5, 2014

Convert Map, HashMap or List/ArrayList to XML and reverse

HashMapToStringXml.java

package pritom;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by pritom on 5/05/14.
 */
public class HashMapToStringXml {
    public static void main(String[] args) {
        Map<Object, Object> hashMap = new HashMap<Object, Object>();
        hashMap.put("firstName", "Pritom");
        hashMap.put("lastName", "Kumar");

        Map<Object, Object> secondMap = new HashMap<Object, Object>();
        secondMap.put("timeIn", "8:00");
        secondMap.put("timeOut", "5:00");
        hashMap.put("timing", secondMap);

        List<Object> list = new ArrayList<Object>();
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(secondMap);
        hashMap.put("contents", list);

        /* Map to XML and reverse */
        String mapToString = objectToString(hashMap);
        Map parsedMap = (Map) stringToObject(mapToString);
        System.out.println("Map to XML: \n" + mapToString + "\nXML to map:\n" + parsedMap);

        /* List to XML and reverse */
        String listToString = objectToString(list);
        List parsedList = (List) stringToObject(listToString);
        System.out.println("List to XML: \n" + listToString + "\nXML to list:\n" + parsedList);
    }

    public static String objectToString(Object hashMap) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        XMLEncoder xmlEncoder = new XMLEncoder(bos);
        xmlEncoder.writeObject(hashMap);
        xmlEncoder.close();
        return bos.toString();
    }

    public static Object stringToObject(String string) {
        XMLDecoder xmlDecoder = new XMLDecoder(new ByteArrayInputStream(string.getBytes()));
        return xmlDecoder.readObject();
    }
}

Output

Map to XML: 
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_45" class="java.beans.XMLDecoder">
 <object class="java.util.HashMap">
  <void method="put">
   <string>lastName</string>
   <string>Kumar</string>
  </void>
  <void method="put">
   <string>contents</string>
   <object class="java.util.ArrayList">
    <void method="add">
     <int>20</int>
    </void>
    <void method="add">
     <int>30</int>
    </void>
    <void method="add">
     <int>40</int>
    </void>
    <void method="add">
     <object class="java.util.HashMap" id="HashMap0">
      <void method="put">
       <string>timeOut</string>
       <string>5:00</string>
      </void>
      <void method="put">
       <string>timeIn</string>
       <string>8:00</string>
      </void>
     </object>
    </void>
   </object>
  </void>
  <void method="put">
   <string>timing</string>
   <object idref="HashMap0"/>
  </void>
  <void method="put">
   <string>firstName</string>
   <string>Pritom</string>
  </void>
 </object>
</java>

XML to map:
{
    lastName=Kumar, 
    contents=[
        20, 
        30, 
        40, 
        {
            timeOut=5:00, 
            timeIn=8:00
        }
    ], 
    firstName=Pritom, 
    timing={
        timeOut=5:00, 
        timeIn=8:00
    }
}



List to XML: 
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_45" class="java.beans.XMLDecoder">
 <object class="java.util.ArrayList">
  <void method="add">
   <int>20</int>
  </void>
  <void method="add">
   <int>30</int>
  </void>
  <void method="add">
   <int>40</int>
  </void>
  <void method="add">
   <object class="java.util.HashMap">
    <void method="put">
     <string>timeOut</string>
     <string>5:00</string>
    </void>
    <void method="put">
     <string>timeIn</string>
     <string>8:00</string>
    </void>
   </object>
  </void>
 </object>
</java>

XML to list:
[20, 30, 40, {timeOut=5:00, timeIn=8:00}]

Friday, May 2, 2014

Iterate over each Entry in HashMap in Java Or loop Map to remove Entries

Example Class: HashMapIterator.java

package com.pkm.annotation;

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

/**
 *
 * @author Pritom
 */
public class HashMapIterator {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("key1", "Value 1");
        map.put("key2", "Value 2");
        map.put("key3", "Value 3");
        map.put("key4", "Value 4");
        map.put("key5", "Value 5");
        
        /* Using Iterator */
        System.out.println("Using Iterator");
        Iterator iterator = map.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) iterator.next();
            System.out.println("Key: " + mapEntry.getKey() + ", Value: " + 
                    mapEntry.getValue());
            if(mapEntry.getKey().toString().equals("key3")) {
                /* Removing without ConcurrentModificationException */
                iterator.remove(); 
            }
        }
        
        /* Using Direct Entry Set */
        System.out.println("\nUsing Direct Entry Set");
        for (Object entry : map.entrySet()) {
            Map.Entry mapEntry = (Map.Entry) entry;
            System.out.println("Key : " + mapEntry.getKey() + ", Value : "
                    + mapEntry.getValue());
        }
        
        /* Using Direct Key Set */
        System.out.println("\nUsing Direct Key Set");
        for (Object entry : map.keySet()) {
            System.out.println("Key : " + entry + ", Value : "
                    + map.get(entry));
        }
    }
}

Example Output:

Using Iterator
Key: key4, Value: Value 4
Key: key3, Value: Value 3
Key: key5, Value: Value 5
Key: key2, Value: Value 2
Key: key1, Value: Value 1

Using Direct Entry Set
Key : key4, Value : Value 4
Key : key5, Value : Value 5
Key : key2, Value : Value 2
Key : key1, Value : Value 1

Using Direct Key Set
Key : key4, Value : Value 4
Key : key5, Value : Value 5
Key : key2, Value : Value 2
Key : key1, Value : Value 1

Tuesday, December 3, 2013

Avoid ConcurrentModificationException when using an Java Iterator

Lets explore this scenario with the following example:
First see two methods and then see last two methods.
For first two methods, used simple arraylist and hashmap, so concurrent exception occurs.
But for the later two methods, used copy on write arraylist and concurrent hashmap, so no problem with the last two methods.

package pritom;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: pritom
 * Date: 3/12/13
 * Time: 4:04 PM
 * To change this template use File | Settings | File Templates.
 */
public class ConcurrentModification {
    public static void main(String[] args) {
        ConcurrentModification.concurrentModificationList();
        ConcurrentModification.concurrentModificationHashMap();
        ConcurrentModification.concurrentModificationConcurrentList();
        ConcurrentModification.concurrentModificationConcurrentHashMap();
    }

    private static void concurrentModificationList() {
        try {
            List<String> myDataList = new ArrayList<String>();
            myDataList.add("1");
            myDataList.add("2");
            myDataList.add("3");
            myDataList.add("4");

            System.out.println("Deleting from List: ");
            for (Iterator it = myDataList.iterator(); it.hasNext();) {
                String myObject = (String) it.next();
                if(myObject.equalsIgnoreCase("2") || myObject.equalsIgnoreCase("4")) {
                    System.out.println("Deleting: " + myObject);
                    myDataList.remove(myObject);
                } else {
                    System.out.println("Not deleting: " + myObject);
                }
            }

            System.out.println("After deleting from List: ");
            for (Iterator it = myDataList.iterator(); it.hasNext();) {
                String myObject = (String) it.next();
                System.out.println("Remaining: " + myObject);
            }
        } catch (Throwable ex) {
            System.out.println("***** Deleting from List error: " + ex.toString() + " *****");
        }
    }

    private static void concurrentModificationHashMap() {
        try {
            Map<String, String> myDataList = new HashMap<String, String>();
            myDataList.put("0", "00");
            myDataList.put("1", "11");
            myDataList.put("2", "22");
            myDataList.put("3", "33");

            System.out.println("\n\nDeleting from Map: ");
            for (Iterator it = myDataList.keySet().iterator(); it.hasNext();) {
                String key = (String) it.next();
                if(key.equalsIgnoreCase("2") || key.equalsIgnoreCase("4")) {
                    System.out.println("Deleting: " + key + " = " + myDataList.get(key));
                    myDataList.remove(key);
                } else {
                    System.out.println("Not deleting: " + key + " = " + myDataList.get(key));
                }
            }

            System.out.println("After deleting from Map: ");
            for (Iterator it = myDataList.keySet().iterator(); it.hasNext();) {
                String key = (String) it.next();
                System.out.println("Remaining: " + key + " = " + myDataList.get(key));
            }
        } catch (Throwable ex) {
            System.out.println("***** Deleting from Map error: " + ex.toString() + " *****\n\n");
        }
    }

    private static void concurrentModificationConcurrentList() {
        try {
            List<String> myDataList = new CopyOnWriteArrayList<String>();
            myDataList.add("1");
            myDataList.add("2");
            myDataList.add("3");
            myDataList.add("4");

            System.out.println("\n\nDeleting from Concurrent List: ");
            for (Iterator it = myDataList.iterator(); it.hasNext();) {
                String myObject = (String) it.next();
                if(myObject.equalsIgnoreCase("2") || myObject.equalsIgnoreCase("4")) {
                    System.out.println("Deleting: " + myObject);
                    myDataList.remove(myObject);
                    myDataList.add("55");
                } else {
                    System.out.println("Not deleting: " + myObject);
                }
            }

            System.out.println("After deleting from Concurrent List: ");
            for (Iterator it = myDataList.iterator(); it.hasNext();) {
                String myObject = (String) it.next();
                System.out.println("Remaining: " + myObject);
            }
        } catch (Throwable ex) {
            System.out.println("***** Deleting from Concurrent List error: " + ex.toString() + " *****");
        }
    }

    private static void concurrentModificationConcurrentHashMap() {
        try {
            Map<String, String> myDataList = new ConcurrentHashMap<String, String>();
            myDataList.put("1", "11");
            myDataList.put("2", "22");
            myDataList.put("3", "33");
            myDataList.put("4", "44");

            System.out.println("\n\nDeleting from Concurrent Map: ");
            for (Iterator it = myDataList.keySet().iterator(); it.hasNext();) {
                String key = (String) it.next();
                if(key.equalsIgnoreCase("2") || key.equalsIgnoreCase("4")) {
                    System.out.println("Deleting: " + key + " = " + myDataList.get(key));
                    myDataList.remove(key);
                    System.out.println("Adding: 5 = 55");
                    myDataList.put("5", "55");
                } else {
                    System.out.println("Not deleting: " + key + " = " + myDataList.get(key));
                }
            }

            System.out.println("After deleting from Concurrent Map: ");
            for (Iterator it = myDataList.keySet().iterator(); it.hasNext();) {
                String key = (String) it.next();
                System.out.println("Remaining: " + key + " = " + myDataList.get(key));
            }
        } catch (Throwable ex) {
            System.out.println("***** Deleting from Concurrent Map error: " + ex.toString() + " *****\n\n");
        }
    }
}

And see the output


Deleting from List: 
Not deleting: 1
Deleting: 2
***** Deleting from List error: java.util.ConcurrentModificationException *****


Deleting from Map: 
Not deleting: 3 = 33
Deleting: 2 = 22
***** Deleting from Map error: java.util.ConcurrentModificationException *****




Deleting from Concurrent List: 
Not deleting: 1
Deleting: 2
Not deleting: 3
Deleting: 4
After deleting from Concurrent List: 
Remaining: 1
Remaining: 3
Remaining: 55
Remaining: 55


Deleting from Concurrent Map: 
Not deleting: 1 = 11
Not deleting: 3 = 33
Deleting: 4 = 44
Adding: 5 = 55
Deleting: 2 = 22
Adding: 5 = 55
After deleting from Concurrent Map: 
Remaining: 1 = 11
Remaining: 5 = 55
Remaining: 3 = 33

To Avoid ConcurrentModificationException in multi-threaded environment (first two methods):
1. You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.
2. You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading.
3. If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.

From the above example its clear that (last two methods):
1. Concurrent Collection classes can be modified avoiding ConcurrentModificationException.
2. In case of CopyOnWriteArrayList, iterator doesn’t accomodate the changes in the list and works on the original list.
3. In case of ConcurrentHashMap, the behavior is not always the same.

Wednesday, November 6, 2013

Merge two hashmap by multiple keys using java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xmlparser;

import java.util.HashMap;

/**
 *
 * @author Pritom K Mondal
 */
public class HashMapMerge {
    public static void main(String[] args) {
        HashMap a = new HashMap();
        
        /**
         * First row
         */
        HashMap b = new HashMap();
        b.put("name", "name-1");
        b.put("roll_0", "roll-11");
        b.put("roll_1", "roll-12");
        HashMap b10 = new HashMap();
        b10.put("item_0", 0);
        b10.put("item_1", 1);
        b.put("item_0", b10);
        
        HashMap c = new HashMap();
        c.put("name", "name-2");
        c.put("roll", "roll-2");
        
        HashMap d = new HashMap();
        d.put("student_0", b);
        d.put("student_1", c);  
        d.put("student_2", "TATA");
        
        /**
         * Second row
         */
        HashMap b1 = new HashMap();
        b1.put("grade", "grade-1");
        HashMap c10 = new HashMap();
        c10.put("item_2", 33);
        c10.put("item_3", 44);
        b1.put("item_0", c10);
        
        HashMap c1 = new HashMap();
        c1.put("grade", "grade-2");
        
        HashMap d1 = new HashMap();
        d1.put("student_0", b1);
        d1.put("student_1", c1); 
        d1.put("student_2", b1);
        
        System.out.println(d);
        System.out.println(d1);
        
        HashMapMerge hashMapMerge = new HashMapMerge();
        a = hashMapMerge.merge(d, d1);
        System.out.println(a);
    }
    
    public HashMap merge(HashMap a, HashMap b) {
        HashMap c = new HashMap();
        
        for(Object key : a.keySet()) {
            String key2 = (String) key;
            Object dup = a.get(key2);
            c.put(key2, dup);
        }
        for(Object key : b.keySet()) {
            String key2 = (String) key;
            Object dup = b.get(key2);
            if(dup instanceof HashMap && c.containsKey(key2) 
                    && c.get(key2) instanceof HashMap) {
                HashMap kk = (HashMap) c.get(key2);
                HashMap p = merge(kk, (HashMap) dup);
                c.put(key2, p);
            } else if(dup instanceof HashMap && c.containsKey(key2) 
                    && !(c.get(key2) instanceof HashMap)) {
                HashMap kk = new HashMap();
                kk.put(key2, c.get(key2));
                HashMap p = merge(kk, (HashMap) dup);
                c.put(key2, p);
            } else {
                c.put(key2, dup);
            } 
        }
        return c;
    }
}

Input map 1:


{
    student_1={
        roll=roll-2, 
        name=name-2
    }, 
    student_0={
        item_0={
            item_1=1, 
            item_0=0
        }, 
        roll_0=roll-11, 
        roll_1=roll-12, 
        name=name-1
    }, 
    student_2=TATA
}

Input map 2:

{
    student_1={
        grade=grade-2
    }, 
    student_0={
        item_0={
            item_3=44, 
            item_2=33
        }, 
        grade=grade-1
    }, 
    student_2={
        item_0={
            item_3=44, 
            item_2=33
        }, 
        grade=grade-1
    }
}

And result map after merge:

{
    student_1={
        roll=roll-2, 
        name=name-2, 
        grade=grade-2
    }, 
    student_0={
        item_0={
            item_1=1, 
            item_0=0, 
            item_3=44, 
            item_2=33
        }, 
        roll_0=roll-11, 
        name=name-1, 
        roll_1=roll-12, 
        grade=grade-1
    }, 
    student_2={
        student_2=TATA, 
        item_0={
            item_3=44, 
            item_2=33
        }, 
        grade=grade-1
    }
}