Tuesday, 31 July 2012

Get Synchronized Map from Java HashMap example


This java example shows how to get a synchronized Map from Java HashMap using synchronizedMap method of Collections class.


import java.util.HashMap;
import java.util.Collections;
import java.util.Map;

public class GetSynchronizedMapFromHashMapExample {

 public static void main(String[] args) {

  // create HashMap object

  HashMap hashMap = new HashMap();

  /**
   * Java HashMap is NOT synchronized. To get synchronized Map from
   * HashMap use static void synchronizedMap(Map map) method of
   * Collections class.
   **/

  Map map = Collections.synchronizedMap(hashMap);

  /**
   * Use this map object to prevent any unsynchronized access to original
   * HashMap object.
   **/

 }
}

Remove value from Java HashMap example


This Java Example shows how to remove a key value pair from HashMap object using remove method.


import java.util.HashMap;

public class RemoveValueFromHashMapExample {

 public static void main(String[] args) {

  // create HashMap object
  HashMap hMap = new HashMap();

  // add key value pairs to HashMap
  hMap.put("1", "One");
  hMap.put("2", "Two");
  hMap.put("3", "Three");

  /**
   * To remove a key value pair from HashMap use Object remove(Object key)
   * method of HashMap class. It returns either the value mapped with the
   * key or null if no value was mapped.
   **/

  Object obj = hMap.remove("2");
  System.out.println(obj + " Removed from HashMap");

 }
}


The output is:


Two Removed from HashMap

Remove all values from Java HashMap example


 This Java Example shows how to remove all values from HashMap object or empty HashMap or clear HashMap using clear method.


import java.util.HashMap;

public class EmptyHashMapExample {

 public static void main(String[] args) {

  // create HashMap object
  HashMap hMap = new HashMap();

  // add key value pairs to HashMap
  hMap.put("1", "One");
  hMap.put("2", "Two");
  hMap.put("3", "Three");

  /**
   * To remove all values or clear HashMap use void clear method() of
   * HashMap class. Clear method removes all key value pairs contained in
   * HashMap.
   **/

  hMap.clear();

  System.out.println("Total key value pairs in HashMap are : "
    + hMap.size());
 }
}



The output is:


Total key value pairs in HashMap are : 0

Get Size of Java HashMap Example


This Java Example shows how to get the size or nubmer of key value pairs stored in HashMap using size method.


import java.util.HashMap;

public class GetSizeOfHashMapExample {

 public static void main(String[] args) {

  // create HashMap object
  HashMap hMap = new HashMap();

  /**
   * To get the size of HashMap use int size() method of HashMap class. It
   * returns the number of key value pairs stored in HashMap object.
   **/
  System.out.println("Size of HashMap : " + hMap.size());

  // add key value pairs to HashMap using put method
  hMap.put("1", "One");
  hMap.put("2", "Two");
  hMap.put("3", "Three");

  System.out.println("Size of HashMap after addition : " + hMap.size());

  // remove one element from HashMap using remove method
  Object obj = hMap.remove("2");

  System.out.println("Size of HashMap after removal : " + hMap.size());
 }
}


The output is:



Size of HashMap : 0
Size of HashMap after addition : 3
Size of HashMap after removal : 2

Check if a particular value exists in Java HashMap example


This Java Example shows how to check if HashMap object contains a particular value using containsValue method of HashMap class.


import java.util.HashMap;

public class CheckParticularValueExistHashMapExample {

 public static void main(String[] args) {

  // create object of HashMap

  HashMap phoneBook = new HashMap();

  // add key value pairs to HashMap

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  /**
   * To check whether a particular value exists in HashMap use boolean
   * containsValue(Object key) method of HashMap class. It returns true if
   * the value is mapped to one or more keys in the HashMap otherwise
   * false.
   **/

  boolean blnExists = phoneBook.containsValue("245745");

  System.out.println("Phone number '245745' exists in HashMap ? : "
    + blnExists);

 }
}



The output is:


Phone number '245745' exists in HashMap ? : true

Check if a particular key exists in Java HashMap example


This Java Example shows how to check if HashMap object contains a particular key using containsKey method of HashMap class.


import java.util.HashMap;

public class CheckParticularKeyExistHashMapExample {

 public static void main(String[] args) {

  // create object of HashMap

  HashMap phoneBook = new HashMap();

  /**
   * Add key value pair to HashMap using Object put(Object key, Object
   * value) method of Java HashMap class, where key and value both are
   * objects put method returns Object which is either the value
   * previously tied to the key or null if no value mapped to the key.
   **/

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  /**
   * To check whether a particular key exists in HashMap use boolean
   * containsKey(Object key) method of HashMap class. It returns true if
   * the HashMap contains mapping for specified key otherwise false.
   **/

  boolean blnExists = phoneBook.containsKey("Joy");
  System.out.println("Name 'Joy' exists in HashMap ? : " + blnExists);

 }
}


The output is:


Name 'Joy' exists in HashMap ? : true

Monday, 30 July 2012

How to get all keys in Java HashMap?


This Java Example shows how to retrieve all keys contained in HashMap using keySet method of Java HashMap class.


import java.util.HashMap;
import java.util.Set;

public class GetKeysFromHashMapExample {

 public static void main(String[] args) {

  // create object of HashMap

  HashMap phoneBook = new HashMap();

  /**
   * Add key value pair to HashMap using Object put(Object key, Object
   * value) method of Java HashMap class, where key and value both are
   * objects put method returns Object which is either the value
   * previously tied to the key or null if no value mapped to the key.
   **/

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  /**
   * Set keySet() - Returns a set view of the keys contained in this map.
   **/

  Set nameSet = phoneBook.keySet();

  System.out.println("Names in the phone book are :");

  for (Object name : nameSet) {
   System.out.println("Name: " + name);
  }

 }
}


The output is:


Names in the phone book are :
Name: Roy
Name: Joy
Name: John

Get Set view of Keys from Java HashMap example


This Java Example shows how to get a Set of keys contained in HashMap using keySet method of Java HashMap class.


import java.util.Iterator;
import java.util.HashMap;
import java.util.Set;

public class GetSetViewOfKeysFromHashMapExample {

 public static void main(String[] args) {

  // create object of HashMap

  HashMap phoneBook = new HashMap();

  /**
   * Add key value pair to HashMap using Object put(Object key, Object
   * value) method of Java HashMap class, where key and value both are
   * objects put method returns Object which is either the value
   * previously tied to the key or null if no value mapped to the key.
   **/

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  /**
   * Set keySet() - Returns a set view of the keys contained in this map.
   **/

  Set nameSet = phoneBook.keySet();

  System.out.println("Names in the phone book are :");

  for (Object name : nameSet) {
   System.out.println("Name: " + name);
  }

  /**
   * Please note that resultant Set object is backed by the HashMap. Any
   * key that is removed from Set will also be removed from original
   * HashMap object. The same is not the case with the element addition.
   **/

  // remove Roy from nameSet

  nameSet.remove("Roy");

  // check if original HashMap still contains entry for name Roy.
  boolean blnExists = phoneBook.containsKey("Roy");
  System.out.println("Does HashMap contain Roy ? " + blnExists);
 }
}


The output is:


Names in the phone book are :
Name: Roy
Name: Joy
Name: John
Does HashMap contain Roy ? false

Iterate through the values of Java HashMap example


This Java Example shows how to iterate through the values contained in the HashMap object.


import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

public class IterateValuesOfHashMapExample {

 public static void main(String[] args) {

  // create HashMap object
  HashMap hMap = new HashMap();

  // add key value pairs to HashMap
  hMap.put("1", "One");
  hMap.put("2", "Two");
  hMap.put("3", "Three");

  /**
   * get Collection of values contained in HashMap using Collection
   * values() method of HashMap class
   **/
  Collection c = hMap.values();

  // obtain an Iterator for Collection
  Iterator itr = c.iterator();
  System.out.println("The map contains values...");
  // iterate through HashMap values iterator
  while (itr.hasNext())
   System.out.println(itr.next());
 }
}


The output is:


The map contains values...
Three
Two
One

Simple Java HashMap example


This simple Java Example shows how to use Java HashMap. It also describes how to add something to HashMap and how to retrieve the value added from HashMap.


import java.util.HashMap;
import java.util.Set;

public class JavaHashMapExample {

 public static void main(String[] args) {

  // create object of HashMap
  HashMap phoneBook = new HashMap();

  /**
   * Add key value pair to HashMap using Object put(Object key, Object
   * value) method of Java HashMap class, where key and value both are
   * objects put method returns Object which is either the value
   * previously tied to the key or null if no value mapped to the key.
   **/

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  // retrieve value using Object get(Object key) method of Java HashMap
  // class
  Object phoneNo = phoneBook.get("Joy");
  System.out.println("Phone number of Joy: " + phoneNo);

  System.out.println("The Map contains...");

  /**
   * Set keySet() - Returns a set view of the keys contained in this map.
   * The set is backed by the map, so changes to the map are reflected in
   * the set, and vice-versa
   **/

  Set nameSet = phoneBook.keySet();
  for (Object name : nameSet) {
   System.out.println("Name: " + name + " Phone: "
     + phoneBook.get(name));
  }

  /**
   * put - If the map previously contained a mapping for this key, the old
   * value is replaced and the put method returns the old value.
   **/

  Object oldPhone = phoneBook.put("Roy", "222222");

  System.out.println("Roy's old phone number:" + oldPhone);
  System.out.println("Roy's new phone number:" + phoneBook.get("Roy"));

 }
}

The output is:


Phone number of Joy: 245786
The Map contains...
Name: Roy Phone: 233783
Name: Joy Phone: 245786
Name: John Phone: 245745
Roy's old phone number:233783
Roy's new phone number:222222

Sunday, 29 July 2012

Convert Array to TreeSet in Java


This Java Example shows how to convert an array to Java TreeSet object using Arrays.asList method.


import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class ArrayToSetExample {

	public static void main(String[] args) {

		Integer[] numbers = { 7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4 };

		/**
		 * To convert an array into a Set, first we convert it into a List using
		 * Arrays.asList method. Next we create a TreeSet and pass the list as
		 * an argument to the constructor.
		 **/

		List< Integer > list = Arrays.asList(numbers);

		Set< Integer > set = new TreeSet< Integer >(list);

		// Display elements of the set

		System.out.println("The set contains...");

		for (Integer n : set) {

			System.out.println(n);
		}
	}
}


The output is:


The set contains...
4
5
6
7
8
9
10

Convert TreeSet to Array in Java


This Java Example shows how to convert Java TreeSet object to an array using toArray method.

import java.util.Set;
import java.util.TreeSet;

public class ConvertTreeSetToArrayExample {

	public static void main(String[] args) {

		// create an TreeSet object

		Set< String > set = new TreeSet< String >();

		// Add elements to the set

		set.add("India");
		set.add("Switzerland");
		set.add("Italy");
		set.add("France");

		System.out.println("TreeSet contains...");

		// display elements of TreeSet

		for (String cnt : set)
			System.out.println(cnt);

		/**
		 * Object[] toArray() - Returns an Object class array containing all of
		 * the elements in this set.Note that we can't explicitly cast the
		 * returned array to some other class type.
		 **/
		Object[] countries = set.toArray();

		System.out.println("Content of array countries=");

		for (Object c : countries) {
			System.out.println(c);
		}
		/**
		 * Object[] toArray(Object[] a) - Returns an array containing all of the
		 * elements in this set; the runtime type of the returned array is that
		 * of the specified array.
		 **/

		String[] countries1 = set.toArray(new String[set.size()]);

		System.out.println("Content of array countries1=");

		for (String c : countries1) {
			System.out.println(c);
		}

	}
}


The output is:


TreeSet contains...
France
India
Italy
Switzerland
Content of array countries=
France
India
Italy
Switzerland
Content of array countries1=
France
India
Italy
Switzerland

Get Tail Set from Java TreeSet example


This Java Example shows how to get the portion of TreeSet containing the values grater than  or equal to the specified value using tailSet method of Java TreeSet class.

import java.util.SortedSet;
import java.util.TreeSet;

public class GetTailSetFromTreeSetExample {

	public static void main(String[] args) {

		// create TreeSet object
		TreeSet tSet = new TreeSet();

		// add elements to TreeSet
		tSet.add("1");
		tSet.add("3");
		tSet.add("2");
		tSet.add("5");
		tSet.add("4");

		/**
		 * To get a Tail Set from Java TreeSet use, SortedSet tailSet(Object
		 * fromElement) method of Java TreeSet class.
		 * 
		 * This method returns the portion of TreeSet containing elements grater
		 * than or equal to fromElement.
		 * 
		 * Please note that, the SortedSet returned by this method is backed by
		 * the original TreeSet. So any changes made to SortedSet will be
		 * reflected back to original TreeSet.
		 **/

		SortedSet sortedSet = tSet.tailSet("2");

		System.out.println("Tail Set Contains : " + sortedSet);

	}
}


The output is:


Tail Set Contains : [2, 3, 4, 5]

Get Head Set from Java TreeSet example


This Java Example shows how to get the portion of TreeSet containing the values less than the specified value using headSet method of Java TreeSet class.


import java.util.SortedSet;
import java.util.TreeSet;

public class GetHeadSetFromTreeSetExample {

	public static void main(String[] args) {

		// create TreeSet object
		TreeSet tSet = new TreeSet();

		// add elements to TreeSet
		tSet.add("1");
		tSet.add("3");
		tSet.add("2");
		tSet.add("5");
		tSet.add("4");

		/**
		 * To get a Head Set from Java TreeSet use, SortedSet headSet(Object
		 * fromElement) method of Java TreeSet class.
		 * 
		 * This method returns the portion of TreeSet containing elements less
		 * than fromElement.
		 * 
		 * Please note that, the SortedSet returned by this method is backed by
		 * the original TreeSet. So any changes made to SortedSet will be
		 * reflected back to original TreeSet.
		 **/

		SortedSet sortedSet = tSet.headSet("3");

		System.out.println("Head Set Contains : " + sortedSet);

	}
}


The output is:


Head Set Contains : [1, 2]

Get Sub Set from Java TreeSet example


This Java Example shows how to get the sub Set from Java TreeSet by giving specific range of values using subSet method of Java TreeSet class.

import java.util.TreeSet;
import java.util.SortedSet;

public class GetSubSetFromTreeSetExample {

	public static void main(String[] args) {

		// create TreeSet object
		TreeSet tSet = new TreeSet();

		// add elements to TreeSet
		tSet.add("1");
		tSet.add("3");
		tSet.add("2");
		tSet.add("5");
		tSet.add("4");

		/**
		 * To get the sub Set from Java TreeSet use, SortedSet subSet(Object
		 * fromElement,Object toElement) method of TreeSet class.
		 * 
		 * This method returns portion of the TreeSet whose elements range from
		 * from (inclusive) to to(exclusive).
		 * 
		 * Please note that, the SortedSet returned by this method is backed by
		 * the original TreeSet. So any changes made to SortedSet will be
		 * reflected back to original TreeSet.
		 **/

		SortedSet sortedSet = tSet.subSet("2", "5");

		System.out.println("Subset Contains : " + sortedSet);

	}
}


The output is:


Subset Contains : [2, 3, 4]

Remove specified element from Java TreeSet example


This Java Example shows how to remove a specified object or element contained in Java TreeSet object using remove method.

import java.util.TreeSet;

public class RemoveSpecifiedElementFromTreeSetExample {

	public static void main(String[] args) {

		// create object of TreeSet
		TreeSet tSet = new TreeSet();

		// add elements to TreeSet object

		tSet.add(1);
		tSet.add(2);
		tSet.add(3);

		System.out.println("TreeSet before removal : " + tSet);

		/**
		 * To remove an element from Java TreeSet object use, boolean
		 * remove(Object o) method. This method removes an element from TreeSet
		 * if it is present and returns true. Otherwise remove method returns
		 * false.
		 **/

		boolean blnRemoved = tSet.remove(2);

		System.out.println("Was 2 removed from TreeSet ? " + blnRemoved);

		System.out.println("TreeSet after removal : " + tSet);
	}
}


The output is:


TreeSet before removal : [1, 2, 3]
Was 2 removed from TreeSet ? true
TreeSet after removal : [1, 3]

Check if a particular value exists in Java TreeSet example


This Java Example shows how to check if TreeSet object contains a particular value using contains method of TreeSet class.


import java.util.TreeSet;
public class CheckValueOfTreeSetExample {

 public static void main(String[] args) {

  // create TreeSet object
  TreeSet tSet = new TreeSet();

  // add elements to TreeSet
  tSet.add("1");
  tSet.add("3");
  tSet.add("2");
  tSet.add("5");
  tSet.add("4");

  /**
   * To check whether a particular value exists in TreeSet use boolean
   * contains(Object value) method of TreeSet class. It returns true if
   * the TreeSet contains the value, otherwise false.
   **/

  boolean blnExists = tSet.contains("3");
  System.out.println("3 exists in TreeSet ? : " + blnExists);
 }
}

The output is:


3 exists in TreeSet ? : true

Remove all elements from Java TreeSet example


This Java Example shows how to remove all elements contained in Java TreeSet or clear TreeSet object using clear method. It also shows how  to check whether TreeSet object is empty or not using isEmpty method.

import java.util.TreeSet;

public class RemoveAllElementsFromTreeSetExample {

 public static void main(String[] args) {

  // create object of TreeSet
  TreeSet tSet = new TreeSet();

  // add elements to TreeSet object
  tSet.add(new Integer("1"));
  tSet.add(new Integer("2"));
  tSet.add(new Integer("3"));

  System.out.println("TreeSet before removal : " + tSet);

  /**
   * To remove all elements from Java TreeSet or to clear TreeSet object
   * use, void clear() method. This method removes all elements from
   * TreeSet.
   **/

  tSet.clear();
  System.out.println("TreeSet after removal : " + tSet);

  /**
   * To check whether TreeSet contains any elements or not use boolean
   * isEmpty() method. This method returns true if the TreeSet does not
   * contains any elements otherwise false.
   **/

  System.out.println("Is TreeSet empty ? " + tSet.isEmpty());

 }
}


The output is:


TreeSet before removal : [1, 2, 3]
TreeSet after removal : []
Is TreeSet empty ? true

Iterate through elements of Java TreeSet example


This Java Example shows how to iterate through elements of Java TreeSet object.

import java.util.Iterator;
import java.util.TreeSet;

public class IterateThroughElementsOfTreeSetExample {

 public static void main(String[] args) {

  // create object of TreeSet
  TreeSet tSet = new TreeSet();

  // add elements to TreeSet object

  tSet.add(1);
  tSet.add(2);
  tSet.add(3);

  // get the Iterator
  Iterator itr = tSet.iterator();

  System.out.println("Using Iterator - TreeSet contains : ");
  while (itr.hasNext())
   System.out.println(itr.next());
  /**
   * We can also use for-each loop available since java1.5 for iterating
   * through elements.
   **/
  System.out.println("Using for-each loop  - TreeSet contains : ");

  for (Object elmt : tSet) {
   System.out.println(elmt);
  }
 }
}


The output is:


Using Iterator - TreeSet contains :
1
2
3
Using for-each loop  - TreeSet contains :
1
2
3

Simple Java TreeSet example


This simple Java Example shows how to use Java TreeSet. It also describes how to add something to TreeSet object using add method.


import java.util.TreeSet;

public class SimpleJavaTreeSetExample {

 public static void main(String[] args) {

  // create object of TreeSet
  TreeSet tSet = new TreeSet();

  /**
   * Add an Object to TreeSet using boolean add(Object obj) method of Java
   * TreeSet class. This method adds an element to TreeSet if it is not
   * already present in TreeSet. It returns true if the element was added
   * to TreeSet, false otherwise.
   **/

  System.out.println("Adding 2:" + tSet.add(2));
  System.out.println("Adding 1:" + tSet.add(1));
  System.out.println("Adding 3:" + tSet.add(3));

  /** A set can't occupy duplicate elements, so returns false. **/

  System.out.println("Again adding 1:" + tSet.add(1));

  /**
   * TreeSet class guarantees that the sorted set will be in ascending
   * element order, sorted according to the natural order of the
   * elements;so here prints 1 2 3.
   **/
  System.out.println("TreeSet contains.." + tSet);
 }
}


The output is:



Adding 2:true
Adding 1:true
Adding 3:true
Again adding 1:false
TreeSet contains..[1, 2, 3]

Get Size of Java TreeSet Example


This example shows how to get the size or number  of elements of a Java TreeSet using size method.


import java.util.TreeSet;

public class GetSizeOfJavaTreeSetExample {

 public static void main(String[] args) {

  // create TreeSet object
  TreeSet tSet = new TreeSet();

  /**
   * To get the size of TreeSet use int size() method of TreeSet class. It
   * returns the number of elements stored in TreeSet object.
   **/
  System.out.println("Size of TreeSet : " + tSet.size());

  // add elements to TreeSet object
  tSet.add(1);
  tSet.add(2);
  tSet.add(3);

  System.out.println("Size of TreeSet after addition : " + tSet.size());

  // remove one element from TreeSet using remove method
  tSet.remove(1);
  System.out.println("Size of TreeSet after removal : " + tSet.size());
 }
}


The output is:


Size of TreeSet : 0
Size of TreeSet after addition : 3
Size of TreeSet after removal : 2

Get lowest and highest value stored in Java TreeSet example


This example shows how to get lowest and highest values stored in TreeSet using first and last methods respectively.


import java.util.TreeSet;
 
public class GetLowestHighestValueTreeSetExample {
 
  public static void main(String[] args) {
 
    //create TreeSet object
    TreeSet tSet = new TreeSet();
   
    //add elements to TreeSet
    tSet.add("1");
    tSet.add("3");
    tSet.add("2");
    tSet.add("5");
    tSet.add("4");
   
    /**
      To get the lowest value currently stored in Java TreeSet use,
      Object first() method of TreeSet class.
     
      This method returns the first or lowest value currently stored in the
      TreeSet object.    
    **/
   
    System.out.println("Lowest value Stored in Java TreeSet is : " + tSet.first());
   
    /**
      To get the highest value currently stored in Java TreeSet use,
      Object last() method of TreeSet class.
     
      This method returns the last or highest value currently stored in the
      TreeSet object.
    **/
   
    System.out.println("Highest value Stored in Java TreeSet is : " + tSet.last());
 
  }
}


The output is:



Lowest value Stored in Java TreeSet is : 1
Highest value Stored in Java TreeSet is : 5

How to remove duplicate element from List ?


This example shows how to remove duplicate elements from a list object.

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

public class CreateUniqueList {
 public static void main(String[] args) {

  /** Create a ArrayList object **/

  ArrayList< String > arrayList = new ArrayList< String >();

  /** Add elements to ArrayList.ArrayList occupies duplicate elements. **/

  arrayList.add("A");
  arrayList.add("B");
  arrayList.add("C");
  arrayList.add("D");
  arrayList.add("A");

  /**
   * HashSet(Collection c) - Constructs a new set containing the unique
   * elements in the specified collection. A set is a collection object
   * that cannot have a duplicate values, so by converting the list to a
   * set the duplicate value will be removed.
   **/

  Set set = new HashSet(arrayList);

  // Creating arrayList with the unique elements.

  arrayList = new ArrayList(set);

  System.out.println("The list contains..." + arrayList);

 }
}


The output is:

The list contains...[D, A, B, C]


Create unique lists of items


This example shows how to remove duplicate elements from a list object.

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

public class CreateUniqueList {
	public static void main(String[] args) {

		/** Create a ArrayList object **/

		ArrayList< string > arrayList = new ArrayList< string >();

		/** Add elements to ArrayList.ArrayList occupies duplicate elements. **/

		arrayList.add("A");
		arrayList.add("B");
		arrayList.add("C");
		arrayList.add("D");
		arrayList.add("A");

		/**
		 * HashSet(Collection c) - Constructs a new set containing the unique
		 * elements in the specified collection. A set is a collection object
		 * that cannot have a duplicate values, so by converting the list to a
		 * set the duplicate value will be removed.
		 **/

		Set set = new HashSet(arrayList);

		System.out.println("The set contains..." + set);

	}
}


The output is:

The set contains...[D, A, B, C]


Get Enumeration over HashSet



This java example shows how to get Enumeration over HashSet using enumeration method of Collections class.

import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;

public class EnumerationOverHashSet {
	public static void main(String[] args) {

		/** Create a HashSet object **/
		HashSet< string > hashSet = new HashSet< string >();

		/** Add elements to HashSet **/
		hashSet.add("A");
		hashSet.add("B");
		hashSet.add("D");
		hashSet.add("E");
		hashSet.add("F");

		/**
		 * Enumeration enumeration(Collection c) - Returns an enumeration over
		 * the specified collection. This provides interoperatbility with legacy
		 * APIs that require an enumeration as input.
		 **/

		Enumeration e = Collections.enumeration(hashSet);
		
		System.out.println("The set contains...");
		
		while (e.hasMoreElements())
			System.out.println(e.nextElement());
	}
}


The output is:



The set contains...
D
E
F
A
B

Copying and Cloning Sets: public Object clone()


Calling the clone() method of a HashSet creates a shallow copy of that HashSet.(the elements of the set aren't duplicated. Both sets will refer to the same elements).


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

public class CloningSet {

 public static void main(String[] a) {

  /** Creating a HashSet object **/

  Set set = new HashSet();

  /** Adding elements to the HashSet **/

  set.add("A");
  set.add("B");
  set.add("C");
  set.add("D");

  /**
   * clone() - Returns a shallow copy of this HashSet instance: the
   * elements themselves are not cloned.
   **/
  Set set2 = ((Set) ((HashSet) set).clone());

  System.out.println(set2);
 }
}


The output is:


[D, A, B, C]

Saturday, 28 July 2012

Making a Collection Read-Only in Java



This java example shows how to make a read-only collection using unmodifiableList, unmodifiableSet and unmodifiableMap  methods of Collections class.


import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MakingCollectionReadOnly {

 public static void main(String[] argv) throws Exception {

  List numberList = new ArrayList();

  numberList.add(1);
  numberList.add(2);
  numberList.add(3);

  /**
   * Returns an unmodifiable view of the specified list. This method
   * allows modules to provide users with "read-only" access to internal
   * lists. Query operations on the returned list "read through" to the
   * specified list, and attempts to modify the returned list, whether
   * direct or via its iterator, result in an
   * UnsupportedOperationException.
   **/

  numberList = Collections.unmodifiableList(numberList);

  try {
   // Attempting to modify the read-only list, throws
   // UnsupportedOperationException

   numberList.set(0, "new value");
  } catch (UnsupportedOperationException e) {
   System.out.println("Can't modify read-only list:"+e);
  }

  Set set = new HashSet();
  set = Collections.unmodifiableSet(set);

  Map map = new HashMap();
  map = Collections.unmodifiableMap(map);
 }
}


The output is:

Can't modify read-only list:java.lang.UnsupportedOperationException


Friday, 27 July 2012

Find Minimum element of Java HashSet Example


This java example shows how to find a minimum element of Java HashSet using min method of Collections class.


import java.util.HashSet;
import java.util.Collections;

public class FindMinimumOfHashSetExample {

 public static void main(String[] args) {

  // create a HashSet object
  HashSet hashSet = new HashSet();

  // Add elements to HashSet
  hashSet.add(123);
  hashSet.add(356);
  hashSet.add(456);
  hashSet.add(500);
  hashSet.add(50);

  /**
   * To find minimum element of Java HashSet use, static Object
   * min(Collection c) method of Collections class.
   * 
   * This method returns the minimum element of Java HashSet according to
   * its natural ordering.
   **/

  Object obj = Collections.min(hashSet);

  System.out.println("Minimum Element of Java HashSet is : " + obj);
 }
}


The output is:



Minimum Element of Java HashSet is : 50

Find maximum element of Java HashSet Example


 This java example shows how to find a maximum element of Java HashSet using max method of Collections class.


import java.util.HashSet;
import java.util.Collections;

public class FindMaximumOfHashSetExample {

 public static void main(String[] args) {

  // create a HashSet object
  HashSet hashSet = new HashSet();

  // Add elements to HashSet
  hashSet.add(123);
  hashSet.add(356);
  hashSet.add(456);
  hashSet.add(500);
  hashSet.add(50);

  /**
   * To find maximum element of Java HashSet use, static Object
   * max(Collection c) method of Collections class.
   * 
   * This method returns the maximum element of Java HashSet according to
   * its natural ordering.
   **/

  Object obj = Collections.max(hashSet);

  System.out.println("Maximum Element of Java HashSet is : " + obj);
 }
}


The output is:



Maximum Element of Java HashSet is : 500

Get Synchronized Set from Java HashSet example


This java example shows how to get a synchronized Set from Java HashSet using synchronizedSet method of Collections class.


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

public class GetSynchronizedSetFromHashSetExample {

 public static void main(String[] args) {

  // create HashSet object
  HashSet hashSet = new HashSet();

  /**
   * Java HashSet is NOT synchronized. To get synchronized Set from
   * HashSet use static void synchronizedSet(Set set) method of
   * Collections class.
   **/

  Set set = Collections.synchronizedSet(hashSet);

  /**
   * Use this set object to prevent any unsynchronized access to original
   * HashSet object.
   **/

 }
}


How to remove duplicate element from array?


This example demonstrates you how to remove duplicate elements from an array using the java.util.HashSet class.

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ArrayRemoveDuplicate {

 public static void main(String[] args) {
  //
  // A string array with duplicate values
  //
  String[] data = { "A", "C", "B", "D", "A", "B", "E", "D", "B", "C" };
  System.out.println("Original array: " + Arrays.toString(data));

  //
  // Convert it to list as we need the list object to create a
  // set object. A set is a collection object that cannot have
  // a duplicate values, so by converting the array to a set
  // the duplicate value will be removed.
  //
  List< string > list = Arrays.asList(data);

  Set< string > set = new HashSet< string >(list);

  System.out.print("Remove duplicate result: ");

  //
  // Create an array to convert the Set back to array.
  // The Set.toArray() method copy the value in the set to the
  // defined array.
  //
  String[] result = new String[set.size()];
  set.toArray(result);
  for (String s : result) {
   System.out.print(s + ", ");
  }
 }
}



The output is:



Original array: [A, C, B, D, A, B, E, D, B, C]
Remove duplicate result: D, E, A, B, C,

Convert Array to HashSet in Java


This Java Example shows how to convert an array to Java HashSet object using Arrays.asList method.


import java.util.*;

public class ArrayToSetExample {

 public static void main(String[] args) {

  Integer[] numbers = { 7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4 };

  /**
   * To convert an array into a Set, first we convert it into a List using
   * Arrays.asList method. Next we create a HashSet and pass the list as
   * an argument to the constructor.
   **/

  List< integer > list = Arrays.asList(numbers);

  Set< integer > set = new HashSet< integer >(list);

  // Display elements of the set

  System.out.println("The set contains...");

  for (Integer n : set) {

   System.out.println(n);
  }
 }
}


The output is:



The set contains...
4
5
6
7
8
9
10

Convert HashSet to Array in Java


This Java Example shows how to convert Java HashSet object to an array using toArray method.


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

public class ConvertHashSetToArrayExample {

 public static void main(String[] args) {

  // create an HashSet object

  Set< string > set = new HashSet< string >();

  // Add elements to the set

  set.add("India");
  set.add("Switzerland");
  set.add("Italy");
  set.add("France");

  System.out.println("HashSet contains...");

  // display elements of HashSet

  for (String cnt : set)
   System.out.println(cnt);

  /**
   * Object[] toArray() - Returns an Object class array containing all of
   * the elements in this set.Note that we can't explicitly cast the
   * returned array to some other class type.
   **/
  Object[] countries = set.toArray();

  System.out.println("Content of array countries=");

  for (Object c : countries) {
   System.out.println(c);
  }
  /**
   * Object[] toArray(Object[] a) - Returns an array containing all of the
   * elements in this set; the runtime type of the returned array is that
   * of the specified array.
   **/

  String[] countries1 = set.toArray(new String[set.size()]);

  System.out.println("Content of array countries1=");

  for (String c : countries1) {
   System.out.println(c);
  }

 }
}


The output is:



HashSet contains...
France
Italy
Switzerland
India
Content of array countries=
France
Italy
Switzerland
India
Content of array countries1=
France
Italy
Switzerland
India

Display all elements in a Java HashSet


This java example shows how to display all elements in a Java HashSet object using Iterator and for-each loop.


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

public class DisplayAllElementsInHashSetExample {

 public static void main(String[] args) {

  // create an HashSet object

  HashSet hashSet = new HashSet();

  // Add elements to HashSet

  hashSet.add(1);
  hashSet.add(2);
  hashSet.add(3);

  System.out.println("HashSet contains : ");

  System.out.println("Display elements using Iterator.");

  Iterator i = hashSet.iterator();
  while (i.hasNext()) {
   System.out.println(i.next());
  }

  System.out
    .println("Display elements using for-each loop(available since jdk1.5)");

  for (Object e : hashSet) {

   System.out.println(e);
  }

 }

}


The output is:




HashSet contains :
Display elements using Iterator.
1
2
3
Display elements using for-each loop(available since jdk1.5)
1
2
3

Check if a particular element exists in Java HashSet Example


This Java Example shows how to check whether an elements is contained in Java HashSet using contains method.


import java.util.HashSet;

public class CheckElementHashSetExample {

 public static void main(String[] args) {

  // create object of HashSet
  HashSet hSet = new HashSet();

  // add elements to HashSet object
  hSet.add(1);
  hSet.add(2);
  hSet.add(3);

  /**
   * To check whether a particular value exists in HashSet use boolean
   * contains(Object value) method of HashSet class. It returns true if
   * the HashSet contains the value, otherwise false.
   **/

  boolean blnExists = hSet.contains(3);
  System.out.println("3 exists in HashSet ? : " + blnExists);

 }
}


The output is:


3 exists in HashSet ? : true

Remove specified element from Java HashSet example


This Java Example shows how to remove a specified object or element contained in Java HashSet object using remove method.


import java.util.HashSet;

public class RemoveSpecifiedElementFromHashSetExample {

 public static void main(String[] args) {

  // create object of HashSet
  HashSet hSet = new HashSet();

  // add elements to HashSet object
  hSet.add(1);
  hSet.add(2);
  hSet.add(3);

  System.out.println("HashSet before removal : " + hSet);

  /**
   * To remove an element from Java HashSet object use, boolean
   * remove(Object o) method. This method removes an element from HashSet
   * if it is present and returns true. Otherwise remove method returns
   * false.
   **/

  boolean blnRemoved = hSet.remove(2);
  System.out.println("Was 2 removed from HashSet ? " + blnRemoved);

  System.out.println("HashSet after removal : " + hSet);
 }
}


The output is:



HashSet before removal : [1, 2, 3]
Was 2 removed from HashSet ? true
HashSet after removal : [1, 3]

Get Size of Java HashSet Example


This Java Example shows how to get the size or nubmer of elements stored in Java HashSet object using size method.


import java.util.HashSet;

public class GetSizeOfJavaHashSetExample {

 public static void main(String[] args) {

  // create HashSet object
  HashSet hSet = new HashSet();

  /**
   * To get the size of HashSet use int size() method of HashSet class. It
   * returns the number of elements stored in HashSet object.
   **/
  System.out.println("Size of HashSet : " + hSet.size());

  // add elements to HashSet object
  hSet.add(new Integer("1"));
  hSet.add(new Integer("2"));
  hSet.add(new Integer("3"));

  System.out.println("Size of HashSet after addition : " + hSet.size());

  // remove one element from HashSet using remove method
  hSet.remove(new Integer("1"));
  System.out.println("Size of HashSet after removal : " + hSet.size());
 }
}


The output is:



Size of HashSet : 0
Size of HashSet after addition : 3
Size of HashSet after removal : 2

Simple Java HashSet example


This simple Java Example shows how to use Java HashSet. It also describes how to add something to HashSet object using add method.


import java.util.HashSet;

public class SimpleHashSetExample {

 public static void main(String[] args) {

  // create object of HashSet

  HashSet hSet = new HashSet();

  /**
   * Add an Object to HashSet using boolean add(Object obj) method of Java
   * HashSet class. This method adds an element to HashSet if it is not
   * already present in HashSet. It returns true if the element was added
   * to HashSet, false otherwise.
   **/

  System.out.println("Adding 1:" + hSet.add(1));
  System.out.println("Adding 2:" + hSet.add(2));
  System.out.println("Adding 3:" + hSet.add(3));

  /**
   * Adding element 2 second time returns false, because set can't occupy
   * duplicate elements.
   **/

  System.out.println("Adding 2:" + hSet.add(2));

  System.out.println("HashSet contains.." + hSet);
 }
}


The output is:



Adding 1:true
Adding 2:true
Adding 3:true
Adding 2:false
HashSet contains..[1, 2, 3]

Remove all elements from Java HashSet example


This Java Example shows how to remove all elements contained in Java HashSet or clear HashSet object using clear method. It also shows how  to check whether HashSet object is empty or not using isEmpty method.


import java.util.HashSet;

public class RemoveAllElementsFromHashSetExample {

 public static void main(String[] args) {

  // create object of HashSet
  HashSet hSet = new HashSet();

  // add elements to HashSet object
  hSet.add(new Integer("1"));
  hSet.add(new Integer("2"));
  hSet.add(new Integer("3"));

  System.out.println("HashSet before removal : " + hSet);

  /**
   * To remove all elements from Java HashSet or to clear HashSet object
   * use, void clear() method. This method removes all elements from
   * HashSet.
   **/

  hSet.clear();
  System.out.println("HashSet after removal : " + hSet);

  /**
   * To check whether HashSet contains any elements or not use boolean
   * isEmpty() method. This method returns true if the HashSet does not
   * contains any elements otherwise false.
   **/

  System.out.println("Is HashSet empty ? " + hSet.isEmpty());

 }
}


The output is:



HashSet before removal : [1, 2, 3]
HashSet after removal : []
Is HashSet empty ? true

Remove specified element from LinkedList Java example


This java example shows how to remove a particular element from Java LinkedList. It also shows how to remove an element at specified index from LinkedList.


import java.util.LinkedList;

public class RemoveElementLinkedListExample {

	public static void main(String[] args) {

		// create LinkedList object
		LinkedList lList = new LinkedList();

		// add elements to LinkedList
		lList.add("1");
		lList.add("2");
		lList.add("3");
		lList.add("4");
		lList.add("5");

		System.out.println("LinkedList contains : " + lList);

		/**
		 * To remove a specified element from Java LinkedList, use boolean
		 * remove(Object obj) method.
		 * 
		 * This method removes the first occurrence of the specified element
		 * from Java LinkedList and returns true if LinkedList contained the
		 * specified element.
		 * 
		 * If LinkedList did not contain the specified element, it remains
		 * unchanged.
		 **/

		boolean isRemoved = lList.remove("2");
		System.out.println("Is 2 removed from LinkedList ? :" + isRemoved);
		System.out.println("LinkedList now contains : " + lList);

		/**
		 * To remove an element at specified index of LinkedList, use Object
		 * remove(int index) method.
		 * 
		 * This method removes an element from specified index and shifts
		 * subsequent elements to the left. It returns an element previously at
		 * the specified index.
		 **/

		Object obj = lList.remove(2);
		System.out.println(obj + " has been removed from LinkedList");
		System.out.println("LinkedList now contains : " + lList);
	}
}


The output is:



LinkedList contains : [1, 2, 3, 4, 5]
Is 2 removed from LinkedList ? :true
LinkedList now contains : [1, 3, 4, 5]
4 has been removed from LinkedList
LinkedList now contains : [1, 3, 5]

Thursday, 26 July 2012

Convert Array to LinkedList in Java


This Java Example shows how to convert an array to Java LinkedList object usingArrays.asList method.


import java.util.Arrays;
import java.util.List;

public class ConvertArrayToLinkedListExample {

 public static void main(String[] args) {

  String[] countries = { "India", "Switzerland", "Italy", "France" };

  /**
   * List asList(Object[] a) - Returns a fixed-size list backed by the
   * specified array(Changes to the returned list "write through" to the
   * array).Operations such as add,remove which affects the list size
   * can't be performed on the returned list;which throws
   * java.lang.UnsupportedOperationException.
   **/

  List list = Arrays.asList(countries);

  System.out.println("List contains...");

  // display elements of List

  for (int index = 0; index < list.size(); index++)
   System.out.println(list.get(index));

  System.out.println("Replace an element in the returned list.");

  /** Works perfectly.set won't affect the returned list size **/

  list.set(1, "America");
  System.out
    .println("After replacing 'Switzerland' with 'America'.Array contains...");

  /**
   * Notice that changes to the returned list will also be reflected in
   * the array.
   **/

  for (String c : countries) {
   System.out.println(c);
  }

  System.out.println("Add an element in the returned list.");

  /**
   * try to change size of the returned list, throws
   * UnsupportedOperationException
   **/
  list.add("Canada");

 }
}


The output is:



List contains...
India
Switzerland
Italy
France
Replace an element in the returned list.
After replacing 'Switzerland' with 'America'.Array contains...
India
America
Italy
France
Add an element in the returned list.
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at ConvertArrayToLinkedListExample.main(ConvertArrayToLinkedListExample.java:50)

Convert LinkedList to Array in Java


This Java Example shows how to convert Java LinkedList object to an array using toArray method.


import java.util.LinkedList;
import java.util.List;

public class ConvertLinkedListToArrayExample {

 public static void main(String[] args) {

  // create an LinkedList object

  List< string > list = new LinkedList< string >();

  // Add elements to the list

  list.add("India");
  list.add("Switzerland");
  list.add("Italy");
  list.add("France");

  System.out.println("LinkedList contains...");

  // display elements of LinkedList

  for (int index = 0; index < list.size(); index++)
   System.out.println(list.get(index));

  /**
   * Object[] toArray() - Returns an Object class array containing all of
   * the elements in this list in the correct order.Note that we can't
   * explicitly cast the returned array to some other class type.
   **/
  Object[] countries = list.toArray();

  System.out.println("Content of array countries=");

  for (Object c : countries) {
   System.out.println(c);
  }
  /**
   * Object[] toArray(Object[] a) - Returns an array containing all of the
   * elements in this list in the correct order; the runtime type of the
   * returned array is that of the specified array.
   **/

  String[] countries1 = list.toArray(new String[list.size()]);

  System.out.println("Content of array countries1=");

  for (String c : countries1) {
   System.out.println(c);
  }

 }
}


The output is:



LinkedList contains...
India
Switzerland
Italy
France
Content of array countries=
India
Switzerland
Italy
France
Content of array countries1=
India
Switzerland
Italy
France

Traverse through LinkedList in reverse direction using Java ListIterator Example


This Java Example shows how to iterate through a LinkedList object in reverse direction using Java ListIterator's previous and hasPrevious methods .


import java.util.LinkedList;
import java.util.ListIterator;

public class TraverseReverseUsingListIteratorExample {

 public static void main(String[] args) {

  // create an LinkedList object
  LinkedList lList = new LinkedList();

  // Add elements to Linkedlist

  lList.add("1");
  lList.add("2");
  lList.add("3");

  /**
   * listIterator(int index) - Returns a list iterator of the elements in
   * this list (in proper sequence), starting at the specified position in
   * this list.An initial call to the previous method would return the
   * element with the specified index minus one.
   **/

  ListIterator listIterator = lList.listIterator(lList.size());

  System.out.println("Linkedlist in the reverse order: ");

  while (listIterator.hasPrevious()) {

   System.out.println(listIterator.previous());
  }

 }

}


The output is:




Linkedlist in the reverse order:
3
2
1

Copying data from one LinkedList to another LinkedList in Java

Many a times you need to create a copy of LinkedList for this purpose you can use addAll(Collection c) method of LinkedList in Java to copy all elements from on LinkedList to another LinkedList in Java.

The complete source code is given below:


import java.util.LinkedList;

public class CopyFromOneLinkedListToAnotherLinkedListExample {

 public static void main(String[] args) {

  // create an LinkedList object
  LinkedList lList = new LinkedList();

  // Add elements to Arraylist

  lList.add("1");
  lList.add("2");
  lList.add("3");

  System.out.println("Original Linkedlist contains : ");

  for (Object e : lList) {

   System.out.println(e);
  }

  // create an LinkedList object for copying.

  LinkedList lListCopy = new LinkedList();

  /**
   * Appends all of the elements in the specified Collection to the end of
   * this list, in the order that they are returned by the specified
   * Collection's Iterator.
   **/

  lListCopy.addAll(lList);

  System.out.println("Copied Linkedlist contains : ");

  for (Object e : lListCopy) {

   System.out.println(e);
  }

 }

}


The output is:




Original Linkedlist contains :
1
2
3
Copied Linkedlist contains :
1
2
3

Display all elements in a Java LinkedList Example


This java example shows how to display all elements in a Java LinkedList object using get method,Iterator , ListIterator and for-each loop.


import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;

public class DisplayAllElementsInLinkedListExample {

 public static void main(String[] args) {

  // create an LinkedList object
  LinkedList lList = new LinkedList();

  // Add elements to Arraylist

  lList.add("1");
  lList.add("2");
  lList.add("3");

  System.out.println("Linkedlist contains : ");

  System.out.println("Display elements using get method.");

  for (int i = 0; i < lList.size(); i++)
   System.out.println(lList.get(i));

  System.out.println("Display elements using Iterator.");

  Iterator i = lList.iterator();
  while (i.hasNext()) {
   System.out.println(i.next());
  }
  System.out.println("Display elements using ListIterator.");

  ListIterator listi = lList.listIterator();

  while (listi.hasNext()) {
   System.out.println(listi.next());
  }

  System.out
    .println("Display elements using for-each loop(available since jdk1.5)");

  for (Object e : lList) {

   System.out.println(e);
  }

 }

}


The output is:



Linkedlist contains :
Display elements using get method.
1
2
3
Display elements using Iterator.
1
2
3
Display elements using ListIterator.
1
2
3
Display elements using for-each loop(available since jdk1.5)
1
2
3

Get Size of Java LinkedList Example


This Java Example shows how to get size of java LinkedList object using size method.


import java.util.LinkedList;

public class GetSizeOfJavaLinkedListExample {

 public static void main(String[] args) {

  // create an LinkedList object

  LinkedList lList = new LinkedList();

  // Add elements to the list

  lList.add("1");
  lList.add("2");
  lList.add("3");

  System.out.println("LinkedList contains...");

  // display elements of LinkedList

  for (int index = 0; index < lList.size(); index++)
   System.out.println(lList.get(index));

  /**
   * size() Returns the number of elements in this list.
   **/

  int sizeOfList = lList.size();

  System.out.println("Size of the LinkedList= " + sizeOfList);

 }
}


The output is:



LinkedList contains...
1
2
3
Size of the LinkedList= 3

Sort elements of Java LinkedList Example


This Java Example shows how to sort the elements of java LinkedList object using Collections.sort method.


import java.util.Collections;
import java.util.LinkedList;

public class SortJavaLinkedListExample {

 public static void main(String[] args) {

  // create an LinkedList object
  LinkedList lList = new LinkedList();

  // Add elements to Arraylist
  lList.add("1");
  lList.add("3");
  lList.add("5");
  lList.add("2");
  lList.add("4");

  /*
   * To sort an LinkedList object, use Collection.sort method. This is a
   * static method. It sorts an LinkedList object's elements into
   * ascending order.
   */
  Collections.sort(lList);

  // display elements of LinkedList
  System.out
    .println("LinkedList elements after sorting in ascending order : ");
  for (int i = 0; i < lList.size(); i++)
   System.out.println(lList.get(i));

 }
}


The output is:




LinkedList elements after sorting in ascending order :
1
2
3
4
5

Replace an element at specified index of Java LinkedList Example


This Java Example shows how to replace an element at specified index of java LinkedList object using set method.


import java.util.LinkedList;

public class ReplaceElementAtSpecifiedIndexLinkedListExample {

 public static void main(String[] args) {

  // create an LinkedList object
  LinkedList lList = new LinkedList();

  // Appends the specified element to the end of this list.

  lList.add("1");
  lList.add("2");
  lList.add("3");

  System.out.println("LinkedList contains...");

  // display elements of LinkedList
  for (int index = 0; index < lList.size(); index++)
   System.out.println(lList.get(index));

  /*
   * To replace an element at the specified index of LinkedList use Object
   * set(int index, Object obj) method. This method replaces the specified
   * element at the specified index in the LinkedList and returns the
   * element previously at the specified position.
   */
  Object replaced = lList.set(1, "REPLACED ELEMENT");

  System.out.println(replaced + " is replaced with new element.");

  System.out.println("Modified LinkedList contains...");

  // display elements of LinkedList
  for (int index = 0; index < lList.size(); index++)
   System.out.println(lList.get(index));

 }
}


The output is:



LinkedList contains...
1
2
3
2 is replaced with new element.
Modified LinkedList contains...
1
REPLACED ELEMENT
3

Remove an element from specified index of Java LinkedList Example


This Java Example shows how to remove an element at specified index of java LinkedList object using remove method.


import java.util.LinkedList;

public class RemoveElementFromLinkedListExample {

 public static void main(String[] args) {

  // create an LinkedList object
  LinkedList lList = new LinkedList();

  // Appends the specified element to the end of this list
  lList.add("1");
  lList.add("2");
  lList.add("3");

  System.out.println("LinkedList contains...");

  // display elements of LinkedList
  for (int index = 0; index < lList.size(); index++)
   System.out.println(lList.get(index));

  /*
   * To remove an element from the specified index of LinkedList use
   * Object remove(int index) method. It returns the element that was
   * removed from the LinkedList.
   */

  Object obj = lList.remove(1);
  System.out.println(obj + " is removed from LinkedList");

  System.out.println("Modified LinkedList contains...");

  // display elements of LinkedList
  for (int index = 0; index < lList.size(); index++)
   System.out.println(lList.get(index));

 }
}


The output is:



LinkedList contains...
1
2
3
2 is removed from LinkedList
Modified LinkedList contains...
1
3

Add an element to specified index of Java LinkedList Example



This Java example shows how to add an element at specified index of Java LinkedList object using add method.


import java.util.LinkedList;

public class AddElementToSpecifiedIndexLinkedListExample {

 public static void main(String[] args) {

  // create an LinkedList object
  LinkedList lList = new LinkedList();

  // Appends the specified element to the end of this list
  lList.add("1");
  lList.add("2");
  lList.add("3");

  System.out.println("LinkedList contains...");

  // display elements of LinkedList
  for (int index = 0; index < lList.size(); index++)
   System.out.println(lList.get(index));

  /**
   * To add an element at the specified index of LinkedList use void
   * add(int index, Object obj) method. This method inserts the specified
   * element at the specified index in the LinkedList.
   **/
  lList.add(1, "INSERTED ELEMENT");

  /**
   * Please note that add method DOES NOT overwrites the element
   * previously at the specified index in the list. It shifts the elements
   * to right side and increasing the list size by 1.
   **/

  System.out.println("After Insertion. LinkedList contains...");

  // display elements of LinkedList
  for (int index = 0; index < lList.size(); index++)
   System.out.println(lList.get(index));

 }
}


The output is:



LinkedList contains...
1
2
3
After Insertion. LinkedList contains...
1
INSERTED ELEMENT
2
3

Get SubList from LinkedList Java example


This java example shows how to get a sublist from Java LinkedList using subList method.


import java.util.LinkedList;
import java.util.List;

public class GetSubListLinkedListJavaExample {

 public static void main(String[] args) {

  // create LinkedList object
  LinkedList lList = new LinkedList();

  // add elements to LinkedList
  lList.add("1");
  lList.add("2");
  lList.add("3");
  lList.add("4");
  lList.add("5");

  System.out.println("LinkedList contains : " + lList);

  /**
   * To get a sublist from Java LinkedList, use List subList(int start,
   * int end) method.
   * 
   * This method returns portion of list containing element from start
   * index inclusive to end index exclusive.
   **/

  List lst = lList.subList(1, 4);
  System.out.println("Sublist contains : " + lst);

  /**
   * Please note that sublist is backed by the original list, so any
   * changes made to sublist will also be reflected back to original
   * LinkedList
   **/

  // remove element from sublist
  lst.remove(2);
  System.out.println("Sublist now contains : " + lst);
  System.out.println("Original LinkedList now contains : " + lList);
 }
}


The output is:



LinkedList contains : [1, 2, 3, 4, 5]
Sublist contains : [2, 3, 4]
Sublist now contains : [2, 3]
Original LinkedList now contains : [1, 2, 3, 5]

Search elements of LinkedList Java example


This java example shows how to search element of Java LinkedList using contains, indexOf and lastIndexOf methods.


import java.util.LinkedList;

public class SearchElementLinkedListExample {

 public static void main(String[] args) {

  // create LinkedList object
  LinkedList lList = new LinkedList();

  // add elements to LinkedList
  lList.add("1");
  lList.add("2");
  lList.add("3");
  lList.add("4");
  lList.add("5");
  lList.add("2");

  /**
   * To check if a particular element exists in a LinkedList, use boolean
   * contains(Object obj) method.
   * 
   * This method returns true if LinkedList contains a particular element,
   * false otherwise.
   **/

  boolean blnElement = lList.contains("4");

  if (blnElement) {
   System.out.println("LinkedList contains 4");
  } else {
   System.out.println("LinkedList does not contain 4");
  }

  /**
   * To search first occurrence of an element of LinkedList, use int
   * indexOf(Object element) method.
   * 
   * This method returns index of first occurrence of element if found in
   * the LinkedList. It returns -1 if element not found.
   **/

  int index = lList.indexOf("2");
  if (index != -1) {
   System.out
     .println("First occurrence of 2 in LinkedList is at index : "
       + index);
  } else {
   System.out.println("LinkedList does not contain 2");
  }

  /**
   * To search last occurrence of an element of LinkedList, use int
   * lastIndexOf(Object element) method.
   * 
   * This method returns index of last occurrence of element if found in
   * the LinkedList. It returns -1 if element not found.
   **/

  index = lList.lastIndexOf("2");
  if (index != -1) {
   System.out
     .println("Last occurrence of 2 in LinkedList is at index : "
       + index);
  } else {
   System.out.println("LinkedList does not contain 2");
  }

 }
}


The output is:



LinkedList contains 4
First occurrence of 2 in LinkedList is at index : 1
Last occurrence of 2 in LinkedList is at index : 5

Remove all elements or clear LinkedList Java example


This java example shows how to remove all elements or clear Java LinkedList using clear method.


import java.util.LinkedList;

public class RemoveAllElementsLinkedListExample {

 public static void main(String[] args) {

  // create LinkedList object

  LinkedList lList = new LinkedList();

  // add elements to LinkedList
  lList.add("1");
  lList.add("2");
  lList.add("3");
  lList.add("4");
  lList.add("5");

  System.out.println("LinkedList contains : " + lList);

  /**
   * To remove all elements of Java LinkedList, use void clear() method.
   * 
   * This method remove all elements from LinkedList object.
   **/

  lList.clear();
  System.out.println("LinkedList now contains : " + lList);

 }
}


The output is:



LinkedList contains : [1, 2, 3, 4, 5]
LinkedList now contains : []

Remove first and last elements of LinkedList Java example


This java example shows how to remove first and last elements of Java LinkedList object using removeFirst and removeLast methods.


import java.util.LinkedList;

public class RemoveFirstLastElementsLinkedListExample {

 public static void main(String[] args) {

  // create LinkedList object
  LinkedList lList = new LinkedList();

  // add elements to LinkedList
  lList.add("1");
  lList.add("2");
  lList.add("3");
  lList.add("4");
  lList.add("5");

  System.out.println("LinkedList contains : " + lList);

  /**
   * To remove first element of Java LinkedList, use Object removeFirst()
   * method.
   * 
   * This method removes first element of LinkedList and shifts the
   * subsequent elements to the left. It returns the element previously at
   * the first index of the LinkedList.
   **/

  Object object = lList.removeFirst();
  System.out.println(object
    + " has been removed from the first index of LinkedList");

  System.out.println("LinkedList now contains : " + lList);

  /**
   * To remove last element of Java LinkedList, use Object removeLast()
   * method.
   * 
   * This method removes last element of LinkedList. It returns the
   * element previously at the last index of the LinkedList.
   **/

  object = lList.removeLast();
  System.out.println(object
    + " has been removed from the last index of LinkedList");

  System.out.println("LinkedList now contains : " + lList);

 }
}


The output is:



LinkedList contains : [1, 2, 3, 4, 5]
1 has been removed from the first index of LinkedList
LinkedList now contains : [2, 3, 4, 5]
5 has been removed from the last index of LinkedList
LinkedList now contains : [2, 3, 4]

Get first and last elements from LinkedList Java example


This java example shows how to get first and last element from Java LinkedList using getFirst and getLast methods.


import java.util.LinkedList;

public class GetFirstAndLastElementLinkedListExample {

 public static void main(String[] args) {

  // create LinkedList object
  LinkedList lList = new LinkedList();

  // add elements to LinkedList

  lList.add("1");
  lList.add("2");
  lList.add("3");
  lList.add("4");
  lList.add("5");

  /**
   * To get first element from Java LinkedList, use Object getFirst()
   * method.
   * 
   * This method returns first element stored in LinkedList.
   **/

  System.out.println("First element of LinkedList is : "
    + lList.getFirst());

  /*
   * To get last element from Java LinkedList, use Object getLast()
   * method.
   * 
   * This method returns last element stored in LinkedList.
   */

  System.out
    .println("Last element of LinkedList is : " + lList.getLast());

 }
}


The output is:



First element of LinkedList is : 1
Last element of LinkedList is : 5

Add elements at beginning and end of LinkedList Java example


This java example shows how to add an element at beginning or at end of java LinkedList object using addFirst and addLast methods.


import java.util.LinkedList;

public class AddElementsAtStartEndLinkedListExample {

 public static void main(String[] args) {

  // create LinkedList object
  LinkedList lList = new LinkedList();

  // add elements to LinkedList
  lList.add("1");
  lList.add("2");
  lList.add("3");
  lList.add("4");
  lList.add("5");

  System.out.println("LinkedList contains : " + lList);

  /**
   * To add an element at the beginning of the LinkedList, use void
   * addFirst(Object obj) method.
   * 
   * This method inserts object at the beginning of the LinkedList.
   **/

  lList.addFirst("0");
  System.out
    .println("After inserting 0 at beginning, LinkedList contains :"
      + lList);

  /*
   * To append an element at end of the LinkedList, use void
   * addLast(Object obj) method.
   * 
   * This method append specified element at the end of the LinkedList.
   */

  lList.addLast("6");
  System.out.println("After appending 6 at end, LinkedList contains :"
    + lList);

 }
}


The output is:




LinkedList contains : [1, 2, 3, 4, 5]
After inserting 0 at beginning, LinkedList contains :[0, 1, 2, 3, 4, 5]
After appending 6 at end, LinkedList contains :[0, 1, 2, 3, 4, 5, 6]

Traverse through ArrayList in reverse direction using Java ListIterator Example


This Java Example shows how to iterate through an ArrayList object in reverse direction using Java ListIterator's previous and hasPrevious methods .


import java.util.ArrayList;
import java.util.ListIterator;

public class TraverseReverseUsingListIteratorExample {

	public static void main(String[] args) {

		// create an ArrayList object
		ArrayList arrayList = new ArrayList();

		// Add elements to Arraylist

		arrayList.add("1");
		arrayList.add("2");
		arrayList.add("3");

		/**
		 * listIterator(int index) - Returns a list iterator of the elements in
		 * this list (in proper sequence), starting at the specified position in
		 * this list.An initial call to the previous method would return the
		 * element with the specified index minus one.
		 **/

		ListIterator listIterator = arrayList.listIterator(arrayList.size());

		System.out.println("Arraylist in the reverse order: ");

		while (listIterator.hasPrevious()) {

			System.out.println(listIterator.previous());
		}

	}

}


The output is:



Arraylist in the reverse order:
3
2
1

How to convert ArrayList to Set in Java with Example

Converting ArrayList to Set in Java means creating a Set implementation like HashSet from an ArrayList full of objects.Before Converting your ArrayList into hashSet do remember that List keep insertion order and guarantees same but Set doesn't have such obligation. Also List allows duplicates but Set doesn't allow any duplicates, which means if you have duplicates in your ArrayList they will be lost when you convert ArrayList to HashSet and that's the reason why sometime size of ArrayList doesn't match with size of HashSet after conversion.

The complete source code is given below:


import java.util.ArrayList;
import java.util.HashSet;

public class ConvertFromArrayListToSetExample {

 public static void main(String[] args) {

  // create an ArrayList object
  ArrayList arrayList = new ArrayList();

  // Add elements to Arraylist

  arrayList.add("1");
  arrayList.add("2");
  arrayList.add("3");
  arrayList.add("2");
  arrayList.add("1");

  System.out.println("Arraylist contains : ");

  for (Object e : arrayList) {

   System.out.println(e);
  }

  /**
   * Constructs a new set containing the elements in the specified
   * collection.
   **/
  HashSet numberSet = new HashSet(arrayList);

  System.out.println("HashSet contains : ");

  for (Object e : numberSet) {

   System.out.println(e);
  }

 }

}


The output is:



Arraylist contains :
1
2
3
2
1
HashSet contains :
3
2
1

Copying data from one ArrayList to another ArrayList in Java


Many a times you need to create a copy of ArrayList for this purpose you can use addAll(Collection c) method of ArrayList in Java to copy all elements from on ArrayList to another ArrayList in Java.

The complete source code is given below:


import java.util.ArrayList;

public class CopyFromOneArrayListToAnotherArrayListExample {

 public static void main(String[] args) {

  // create an ArrayList object
  ArrayList arrayList = new ArrayList();

  // Add elements to Arraylist

  arrayList.add("1");
  arrayList.add("2");
  arrayList.add("3");

  System.out.println("Original Arraylist contains : ");

  for (Object e : arrayList) {

   System.out.println(e);
  }

  // create an ArrayList object for copying.

  ArrayList arrayListCopy = new ArrayList();

  /**
   * Appends all of the elements in the specified Collection to the end of
   * this list, in the order that they are returned by the specified
   * Collection's Iterator.
   **/

  arrayListCopy.addAll(arrayList);

  System.out.println("Copied Arraylist contains : ");

  for (Object e : arrayListCopy) {

   System.out.println(e);
  }

 }

}


The output is:



Original Arraylist contains :
1
2
3
Copied Arraylist contains :
1
2
3

Display all elements in a Java arraylist



This java example shows how to display all elements in a Java ArrayList object using get method,Iterator , ListIterator and for-each loop.


import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

public class DisplayAllElementsInArrayListExample {

 public static void main(String[] args) {

  // create an ArrayList object
  ArrayList arrayList = new ArrayList();

  // Add elements to Arraylist

  arrayList.add("1");
  arrayList.add("2");
  arrayList.add("3");

  System.out.println("Arraylist contains : ");

  System.out.println("Display elements using get method.");

  for (int i = 0; i < arrayList.size(); i++)
   System.out.println(arrayList.get(i));

  System.out.println("Display elements using Iterator.");

  Iterator i = arrayList.iterator();
  while (i.hasNext()) {
   System.out.println(i.next());
  }
  System.out.println("Display elements using ListIterator.");

  ListIterator listi = arrayList.listIterator();

  while (listi.hasNext()) {
   System.out.println(listi.next());
  }

  System.out
    .println("Display elements using for-each loop(available since jdk1.5)");

  for (Object e : arrayList) {

   System.out.println(e);
  }

 }

}


The output is:




Arraylist contains :
Display elements using get method.
1
2
3
Display elements using Iterator.
1
2
3
Display elements using ListIterator.
1
2
3
Display elements using for-each loop(available since jdk1.5)
1
2
3

Get Synchronized List from Java ArrayList example


This java example shows how to get a synchronized list from Java ArrayList using synchronizedList method of Collections class.


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GetSynchronizedListFromArrayListExample {

 public static void main(String[] args) {

  // create an ArrayList object
  ArrayList arrayList = new ArrayList();

  /**
   * Java ArrayList is NOT synchronized. To get synchronized list from
   * ArrayList use static void synchronizedList(List list) method of
   * Collections class.
   **/

  List list = Collections.synchronizedList(arrayList);

  /**
   * Use this list object to prevent any unsynchronized access to original
   * ArrayList object.
   **/

 }
}

Convert Array to ArrayList in Java


This Java Example shows how to convert an array to Java ArrayList object using Arrays.asList method.


import java.util.Arrays;
import java.util.List;

public class ConvertArrayToArrayListExample {

 public static void main(String[] args) {

  String[] countries = { "India", "Switzerland", "Italy", "France" };

  /**
   * List asList(Object[] a) - Returns a fixed-size list backed by the
   * specified array(Changes to the returned list "write through" to the
   * array).Operations such as add,remove which affects the list size
   * can't be performed on the returned list;which throws
   * java.lang.UnsupportedOperationException.
   **/

  List list = Arrays.asList(countries);

  System.out.println("List contains...");

  // display elements of List

  for (int index = 0; index < list.size(); index++)
   System.out.println(list.get(index));

  System.out.println("Replace an element in the returned list.");

  /** Works perfectly.set won't affect the returned list size **/

  list.set(1, "America");
  System.out
    .println("After replacing 'Switzerland' with 'America'.Array contains...");

  /**
   * Notice that changes to the returned list will also be reflected in
   * the array.
   **/

  for (String c : countries) {
   System.out.println(c);
  }

  System.out.println("Add an element in the returned list.");

  /**
   * try to change size of the returned list, throws
   * UnsupportedOperationException
   **/
  list.add("Canada");

 }
}


The output is :



List contains...
India
Switzerland
Italy
France
Replace an element in the returned list.
After replacing 'Switzerland' with 'America'.Array contains...
India
America
Italy
France
Add an element in the returned list.
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at ConvertArrayToArrayListExample.main(ConvertArrayToArrayListExample.java:51)

Wednesday, 25 July 2012

Convert ArrayList to Array in Java

This Java Example shows how to convert Java ArrayList object to an array using toArray method.


import java.util.ArrayList;
import java.util.List;

public class ConvertArrayListToArrayExample {

 public static void main(String[] args) {

  // create an ArrayList object

  List< string > list = new ArrayList< string >();

  // Add elements to the list

  list.add("India");
  list.add("Switzerland");
  list.add("Italy");
  list.add("France");

  System.out.println("ArrayList contains...");

  // display elements of ArrayList

  for (int index = 0; index < list.size(); index++)
   System.out.println(list.get(index));

  /**
   * Object[] toArray() - Returns an Object class array containing all of
   * the elements in this list in the correct order.Note that we can't
   * explicitly cast the returned array to some other class type.
   **/
  Object[] countries = list.toArray();

  System.out.println("Content of array countries=");

  for (Object c : countries) {
   System.out.println(c);
  }
  /**
   * Object[] toArray(Object[] a) - Returns an array containing all of the
   * elements in this list in the correct order; the runtime type of the
   * returned array is that of the specified array.
   **/

  String[] countries1 = list.toArray(new String[list.size()]);

  System.out.println("Content of array countries1=");

  for (String c : countries1) {
   System.out.println(c);
  }

 }
}


The output is:



ArrayList contains...
India
Switzerland
Italy
France
Content of array countries=
India
Switzerland
Italy
France
Content of array countries1=
India
Switzerland
Italy
France

Get Size of Java ArrayList Example


This Java Example shows how to get size of java ArrayList object using size method.

import java.util.ArrayList;

public class GetSizeOfJavaArrayListExample {

 public static void main(String[] args) {

  // create an ArrayList object

  ArrayList arrayList = new ArrayList();

  // Add elements to the list

  arrayList.add("1");
  arrayList.add("2");
  arrayList.add("3");

  System.out.println("ArrayList contains...");

  // display elements of ArrayList

  for (int index = 0; index < arrayList.size(); index++)
   System.out.println(arrayList.get(index));

  /**
   * size() Returns the number of elements in this list.
   **/

  int sizeOfList = arrayList.size();

  System.out.println("Size of the ArrayList= " + sizeOfList);

 }
}


The output is:



ArrayList contains...
1
2
3
Size of the ArrayList= 3

Get Sub List of Java ArrayList Example


This Java Example shows how to get sub list of java ArrayList using subList   method by providing start and end index.


import java.util.ArrayList;
import java.util.List;

public class GetSubListOfJavaArrayListExample {

 public static void main(String[] args) {

  // create an ArrayList object
  ArrayList arrayList = new ArrayList();

  // Add elements to Arraylist
  arrayList.add("1");
  arrayList.add("2");
  arrayList.add("3");
  arrayList.add("4");
  arrayList.add("5");

  /**
   * To get a sub list of Java ArrayList use List subList(int startIndex,
   * int endIndex) method. This method returns an object of type List
   * containing elements from startIndex to endIndex - 1.
   **/

  List lst = arrayList.subList(1, 3);

  // display elements of sub list.
  System.out.println("Sub list contains : ");
  for (int i = 0; i < lst.size(); i++)
   System.out.println(lst.get(i));

  /**
   * Sub List returned by subList method is backed by original Arraylist.
   * So any changes made to sub list will also be REFLECTED in the
   * original Arraylist.
   **/
  // remove one element from sub list
  Object obj = lst.remove(0);
  System.out.println(obj + " is removed from sub list");

  // print original ArrayList
  System.out.println("After removing " + obj
    + " from sub list, original ArrayList contains : ");
  for (int i = 0; i < arrayList.size(); i++)
   System.out.println(arrayList.get(i));

 }

}


The output is:



Sub list contains :
2
3
2 is removed from sub list
After removing 2 from sub list, original ArrayList contains :
1
3
4
5

Sort elements of Java ArrayList Example


This Java Example shows how to sort the elements of java ArrayList object using Collections.sort method.


import java.util.ArrayList;
import java.util.Collections;

public class SortJavaArrayListExample {

 public static void main(String[] args) {

  // create an ArrayList object
  ArrayList arrayList = new ArrayList();

  // Add elements to Arraylist
  arrayList.add("1");
  arrayList.add("3");
  arrayList.add("5");
  arrayList.add("2");
  arrayList.add("4");

  /*
   * To sort an ArrayList object, use Collection.sort method. This is a
   * static method. It sorts an ArrayList object's elements into ascending
   * order.
   */
  Collections.sort(arrayList);

  // display elements of ArrayList
  System.out
    .println("ArrayList elements after sorting in ascending order : ");
  for (int i = 0; i < arrayList.size(); i++)
   System.out.println(arrayList.get(i));

 }
}


The output is:



ArrayList elements after sorting in ascending order :
1
2
3
4
5

Remove all elements from Java ArrayList Example


This Java Example shows how to remove all elements from java ArrayList object using clear method.



import java.util.ArrayList;

public class RemoveAllElementsOfArrayListExample {

 public static void main(String[] args) {

  // create an ArrayList object
  ArrayList arrayList = new ArrayList();

  // Add elements to Arraylist

  arrayList.add("1");
  arrayList.add("2");
  arrayList.add("3");

  System.out.println("Size of ArrayList before removing elements : "
    + arrayList.size());
  /*
   * To remove all elements from the ArrayList use void clear() method.
   */
  arrayList.clear();
  System.out.println("Size of ArrayList after removing elements : "
    + arrayList.size());
 }
}


The output is:



Size of ArrayList before removing elements : 3
Size of ArrayList after removing elements : 0

Search an element of Java ArrayList Example

This Java Example shows how to search an element of java ArrayList object using contains, indexOf and lastIndexOf methods.


import java.util.ArrayList;

public class SearchAnElementInArrayListExample {

 public static void main(String[] args) {

  // create an ArrayList object
  ArrayList arrayList = new ArrayList();

  // Add elements to Arraylist

  arrayList.add("1");
  arrayList.add("2");
  arrayList.add("3");
  arrayList.add("4");
  arrayList.add("5");
  arrayList.add("1");
  arrayList.add("2");

  /**
   * To check whether the specified element exists in Java ArrayList use
   * boolean contains(Object element) method. It returns true if the
   * ArrayList contains the specified objct, false otherwise.
   **/

  boolean blnFound = arrayList.contains("2");
  System.out.println("Does arrayList contain 2 ? " + blnFound);

  /**
   * To get an index of specified element in ArrayList use int
   * indexOf(Object element) method. This method returns the index of the
   * specified element in ArrayList. It returns -1 if not found.
   **/

  int index = arrayList.indexOf("4");
  if (index == -1)
   System.out.println("ArrayList does not contain 4");
  else
   System.out.println("ArrayList contains 4 at index :" + index);

  /**
   * To get last index of specified element in ArrayList use int
   * lastIndexOf(Object element) method. This method returns index of the
   * last occurrence of the specified element in ArrayList. It returns -1
   * if not found.
   **/

  int lastIndex = arrayList.lastIndexOf("1");
  if (lastIndex == -1)
   System.out.println("ArrayList does not contain 1");
  else
   System.out
     .println("Last occurrence of 1 in ArrayList is at index :"
       + lastIndex);

 }
}


The output is:



Does arrayList contain 2 ? true
ArrayList contains 4 at index :3
Last occurrence of 1 in ArrayList is at index :5

Replace an element at specified index of Java ArrayList Example


This Java Example shows how to replace an element at specified index of java ArrayList object using set method.


import java.util.ArrayList;

public class ReplaceElementAtSpecifiedIndexArrayListExample {

	public static void main(String[] args) {

		// create an ArrayList object
		ArrayList arrayList = new ArrayList();

		// Appends the specified element to the end of this list.

		arrayList.add("1");
		arrayList.add("2");
		arrayList.add("3");

		System.out.println("ArrayList contains...");

		// display elements of ArrayList
		for (int index = 0; index < arrayList.size(); index++)
			System.out.println(arrayList.get(index));

		/*
		 * To replace an element at the specified index of ArrayList use Object
		 * set(int index, Object obj) method. This method replaces the specified
		 * element at the specified index in the ArrayList and returns the
		 * element previously at the specified position.
		 */
		Object replaced = arrayList.set(1, "REPLACED ELEMENT");

		System.out.println(replaced + " is replaced with new element.");

		System.out.println("Modified ArrayList contains...");

		// display elements of ArrayList
		for (int index = 0; index < arrayList.size(); index++)
			System.out.println(arrayList.get(index));

	}
}


The output is:



ArrayList contains...
1
2
3
2 is replaced with new element.
Modified ArrayList contains...
1
REPLACED ELEMENT
3

Remove an element from specified index of Java ArrayList Example

This Java Example shows how to remove an element at specified index of java ArrayList object using remove method.


import java.util.ArrayList;

public class RemoveElementFromArrayListExample {

 public static void main(String[] args) {

  // create an ArrayList object
  ArrayList arrayList = new ArrayList();

  // Appends the specified element to the end of this list
  arrayList.add("1");
  arrayList.add("2");
  arrayList.add("3");

  System.out.println("ArrayList contains...");

  // display elements of ArrayList
  for (int index = 0; index < arrayList.size(); index++)
   System.out.println(arrayList.get(index));

  /*
   * To remove an element from the specified index of ArrayList use Object
   * remove(int index) method. It returns the element that was removed
   * from the ArrayList.
   */

  Object obj = arrayList.remove(1);
  System.out.println(obj + " is removed from ArrayList");

  System.out.println("Modified ArrayList contains...");

  // display elements of ArrayList
  for (int index = 0; index < arrayList.size(); index++)
   System.out.println(arrayList.get(index));

 }
}


The output is:


ArrayList contains...
1
2
3
2 is removed from ArrayList
Modified ArrayList contains...
1
3

Add an element to specified index of Java ArrayList Example

This Java example shows how to add an element at specified index of Java ArrayList object using add method.


import java.util.ArrayList;

public class AddElementToSpecifiedIndexArrayListExample {

 public static void main(String[] args) {

  // create an ArrayList object
  ArrayList arrayList = new ArrayList();

  // Appends the specified element to the end of this list
  arrayList.add("1");
  arrayList.add("2");
  arrayList.add("3");

  System.out.println("ArrayList contains...");

  // display elements of ArrayList
  for (int index = 0; index < arrayList.size(); index++)
   System.out.println(arrayList.get(index));

  /**
   * To add an element at the specified index of ArrayList use void
   * add(int index, Object obj) method. This method inserts the specified
   * element at the specified index in the ArrayList.
   **/
  arrayList.add(1, "INSERTED ELEMENT");

  /**
   * Please note that add method DOES NOT overwrites the element
   * previously at the specified index in the list. It shifts the elements
   * to right side and increasing the list size by 1.
   **/

  System.out.println("After Insertion. ArrayList contains...");

  // display elements of ArrayList
  for (int index = 0; index < arrayList.size(); index++)
   System.out.println(arrayList.get(index));

 }
}


The output is



ArrayList contains...
 1
 2
 3
 After Insertion. ArrayList contains...
 1
 INSERTED ELEMENT
 2
 3

java.lang.Thread - Objective Questions - Part 3

1)
A timeout argument can be passed to which of the following methods?

1. wait()
2. notify()
3. sleep()
4. join()
5. yield()
6. notifyAll()

Answer:wait(),sleep(),join()

wait(long timeout)-Causes current thread to wait until either another thread invokes the notify()  method orthe notifyAll()  method for this object, or a specified amount of time has elapsed.
join(long millis)-It tellsthe current thread to wait until either the other thread to complete or time has elapsed.
sleep(long millis)-causes the current thread to wait for a specified amount of time.


2)

Which kind of variable would you prefer to synchronize on?