Showing posts with label list. Show all posts
Showing posts with label list. Show all posts

Monday, November 14, 2016

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}]

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.

Tuesday, October 8, 2013

Groovy Goodness: Sorting a List of Map by specific Key

Sorting a Map by value with Groovy is very simple, due to the added ‘sort’ method on the Map interface.
def hashMap = "fields": {
      "field_3": {
        "order": 4
      },
      "field_2": {
        "order": 3
      },
      "field_1": {
        "order": 2     
    },
      "field_0": {
        "order": 6   
      }
    }

hashMap.sort { a , b -> a.value.order <=> b.value.order }

Tuesday, October 1, 2013

Grails pagination on a ArrayList

In my recent grails project, i needed to paginate on an array list, so I wrote a function and thought would share it with you all.

public List getFilteredList(int max, int offset) {
    max = Math.min(max ?: 25, 100)
    offset = (offset && offset > 0) ?: 0

    List names = getNames() //Loads the complete list
    int total = names.size()
    int upperLimit = findUpperIndex(offset, max, total)
    List filteredNames = names.getAt(offset..upperLimit)
    return filteredNames
}

private static int findUpperIndex(int offset, int max, int total) {
    max = offset + max - 1
    if (max >= total) {
        max -= max - total + 1
    }
    return max
}
So now if offset=20 and max=10, total = 28 so this will generate a list from 21st to 28th elements of the main list.

Monday, May 6, 2013

Get event click list item in J2ME

In midp a list is actually more like a menu with a selection of choices. You have to set a command on it, so that in your command action you can dispatch on this command, get the selection form the menu and set the next screen accordingly.

package com.pkm;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;

/**
 * @author User
 */
public class HelloMIDlet extends MIDlet implements javax.microedition.lcdui.CommandListener {
    private Display display;
    
    private Form form = new Form("Sign In Please");
    
    private Command submit = new Command("Submit", Command.SCREEN, 1);
    private Command exit = new Command("Exit", Command.EXIT, 1);
    private Command contactList = new Command("contactList", Command.OK, 1);
    private Command selection=new Command("Select", Command.ITEM, 1);
    
    List services;
    
    private TextField userName = new TextField("First Name:", "", 50, TextField.ANY);
    private TextField password = new TextField("Password", "", 30, TextField.PASSWORD);

    public HelloMIDlet() {
        display = Display.getDisplay(this);
        form.addCommand(submit);
        form.addCommand(exit);
        form.append(userName);
        form.append(password);
        form.setCommandListener(this);
    }

    public void startApp() {
        display.setCurrent(form);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command command, Displayable displayable) {
        if (command == submit) {
            validateUser(userName.getString(), password.getString());
        } else if (command == exit) {
            destroyApp(false);
            notifyDestroyed();
        } else if (command == contactList) {
            ContactList contactList = new ContactList("Contact List", this);
            display.setCurrent(contactList);
        } else if (command == selection) {
            int index = services.getSelectedIndex();
            Alert alert = new Alert("Your selection",
            "You chose " + services.getString(index) + ".",
            null, AlertType.INFO);
            Display.getDisplay(this).setCurrent(alert, services);
        }
    }
    
    public void validateUser(String name, String password) {
        if (name.equals("a") && password.equals("a")) {
            menu();
        } else {
            tryAgain();
        }
    }
    
    public void menu() {
        services = new List("Choose one", List.IMPLICIT);
        services.append("Check Mail", null);
        services.append("Compose", null);
        services.append("Addresses", null);
        services.append("Options", null);
        services.append("Sign Out", null);
        services.setSelectCommand(selection);
        services.addCommand(contactList);
        services.setCommandListener(this);
        
        display.setCurrent(services);
    }

    public void tryAgain() {
        Alert error = new Alert("Login Incorrect", "Please try again", null, AlertType.ERROR);
        error.setTimeout(Alert.FOREVER);
        userName.setString("");
        password.setString("");
        display.setCurrent(error, form);
    }

    void displayMainMIDlet() {
        menu();
    }
}

Friday, April 26, 2013

Android, show list of items and bind click on list items

Call list item intent from your application class:
Intent intent = new Intent(MyFirstAppActivity.this, LentList.class);
startActivity(intent);

Here, MyFirstAppActivity is the main class and LentList is the class where list items would show.

First, create a layout file under layout folder, such named list.xml and paste the following content:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" />
</LinearLayout>

Now create LentIist.java class:
public class LentList extends ListActivity

private ArrayList<LentPerson> liLentPerson;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list);
    this.generateLentPersons();
    setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1, liLentPerson.toArray()));
}

Function: generateLentPersons() is as following:
private ArrayList<Person> getPersons() {
    ArrayList<Person> liPerson = new ArrayList<Person>();
    person = new Person(1, "Pritom Kumar", "Software Engineer", "KU");
    return liPerson;
}
Function MyAdapter is as following:
private class MyAdapter extends ArrayAdapter<Object> {
	public MyAdapter(Context context, int resource, Object[] persons) {
		super(context, resource, persons);
	}
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View row = inflater.inflate(R.layout.list_each, parent, false);	
		LentPerson p = (Person) getItem(position);
		
		TextView textView1 = (TextView) row.findViewById(R.id.textView1);
		TextView textView2 = (TextView) row.findViewById(R.id.textView2);	
		TextView textView3 = (TextView) row.findViewById(R.id.textView3);
		
		textView1.setText(p.getName()); /* Pritom Kumar */
		textView2.setText(p.getDesignation()); /* Software Engineer */
		textView3.setText(p.getUniversity()); /* KU */
                /* Bind event on row click */
		row.setOnClickListener(new OnItemClickListener(p));
		return row;
	}
} 
 

Layout file list_each.xml as following:
<?xml version="1.0" encoding="UTF-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/tableLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Small Text"
            android:textAppearance="?android:attr/textAppearanceSmall" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Small Text"
            android:textAppearance="?android:attr/textAppearanceSmall" />

    </TableLayout>
    
Function OnItemClickListener is as following:
private class OnItemClickListener implements OnClickListener{
	private LentPerson p;
	public OnItemClickListener(LentPerson p) {
		this.p = p;
	}
	public void onClick(View arg0) {
		Toast.makeText(LentList.this, p.getName(), Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(LentList.this, PersonDetails.class);
		intent.putExtra("personId", p.getId());
		intent.putExtra("txtName", p.getName());
		intent.putExtra("txtBorrower", p.getborrower());
		intent.putExtra("txtCategory", p.getCategory());
		startActivity(intent);
	} 
}

Java class  PersonDetails is as following:
package com.pkm.andrd;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class PersonDetails extends Activity {
	private TextView textView2;
	private TextView textView4;
	private TextView textView6;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.persondetails);
		
		textView2 = (TextView) findViewById(R.id.textView2);
		textView4 = (TextView) findViewById(R.id.textView4);
		textView6 = (TextView) findViewById(R.id.textView6);

		textView2.setText(getIntent().getExtras().getString("txtName"));
		textView4.setText(getIntent().getExtras().getString("txtBorrower"));
		textView6.setText(getIntent().getExtras().getString("txtCategory"));
	}
}
Layout  R.layout.persondetails is as following:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent" android:layout_height="match_parent"
	android:orientation="vertical">



    <TextView
        android:id="@+id/textView7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/s2610132158"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >




            <TextView
                android:id="@+id/textView1"
            android:layout_width="90dp"
                android:layout_height="wrap_content"
                android:text="@string/Name"
                android:textAppearance="?android:attr/textAppearanceMedium" />

        </LinearLayout>



        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </TableRow>



    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >



        <TextView
            android:id="@+id/textView3"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="@string/borrower"
            android:textAppearance="?android:attr/textAppearanceMedium" />



        <TextView
            android:id="@+id/textView4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >


        <TextView
            android:id="@+id/textView5"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="@string/category"
            android:textAppearance="?android:attr/textAppearanceMedium" />



        <TextView
            android:id="@+id/textView6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </LinearLayout>

</LinearLayout>

Make sure you have the following entry in your manifest file under application tag:
<activity android:name=".LentList" />
<activity android:name=".PersonDetails" />