+ All Categories
Home > Documents > Collection Examples

Collection Examples

Date post: 25-Aug-2014
Category:
Upload: knv-chaitanya
View: 110 times
Download: 0 times
Share this document with a friend
Popular Tags:
36
Java – Run program automatically on tomcat startup Every one who is using tomcat and java, face problem of starting program automatically on tomcat startup. To run java program automatically on tomcat startup, need to use Servlet and this Servlet initialized on tomcat startup automatically. How it will work, we will explain in next phase. Most of small and big web application needs to execute some queries and java program in background, without opening on the web browser and user interaction. If we want to start scheduler for newsletter which has to send newsletter on everyday in evening, you have to start timer when tomcat started. This timer works in background for waiting to come evening to send newsletter, without opening script on web browser and manual process by user. To execute our program, we have to use Servlet and Servlet should define in deployment descriptor web.xml file in WEB-INF. web.xml file contain tags <load-on-startup> and <servlet> tag. Servlet tag keep information of Servlet class. When tomcat starts, all Servlet loads in web container and init method of Servlet loaded first. Any java statement in init method of Servlet can be executed on running tomcat startup batch or shell. In init method we can define our scripts which have to be executed e.g. sending emails, sending newsletters, starting scheduler. <?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>ServletInitializer</servlet-name> <servlet-class>com.cron.ServletInitializer</servlet-class> <load-on-startup>1</load-on-startup> </servlet>
Transcript
Page 1: Collection Examples

Java – Run program automatically on tomcat startupEvery one who is using tomcat and java, face problem of starting program automatically on tomcat startup. To run java program automatically on tomcat startup, need to use Servlet and this Servlet initialized on tomcat startup automatically.

How it will work, we will explain in next phase. Most of small and big web application needs to execute some queries and java program in background, without opening on the web browser and user interaction.

If we want to start scheduler for newsletter which has to send newsletter on everyday in evening, you have to start timer when tomcat started. This timer works in background for waiting to come evening to send newsletter, without opening script on web browser and manual process by user.

To execute our program, we have to use Servlet and Servlet should define in deployment descriptor web.xml file in WEB-INF. web.xml file contain tags <load-on-startup> and <servlet> tag. Servlet tag keep information of Servlet class. When tomcat starts, all Servlet loads in web container and init method of Servlet loaded first. Any java statement in init method of Servlet can be executed on running tomcat startup batch or shell.

In init method we can define our scripts which have to be executed e.g. sending emails, sending newsletters, starting scheduler.

<?xml version="1.0" encoding="UTF-8"?><web-app>

<servlet> <servlet-name>ServletInitializer</servlet-name> <servlet-class>com.cron.ServletInitializer</servlet-class> <load-on-startup>1</load-on-startup> </servlet>

</web-app>

ServletInitializer.java

package com.cron;

import java.io.*;

import javax.servlet.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletResponse;

public class ServletInitializer extends HttpServlet{

Page 2: Collection Examples

public void init() throws ServletException { /// Automatically java script can run here System.out.println("************"); System.out.println("*** Servlet Initialized successfully ***.."); System.out.println("***********");

}

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}}

Start tomcat and see output in console mode

Hashtable example in JavaHashtable was part of the original java.util and is a concrete implementation of a Dictionary. However, Java 2 reengineered Hashtable so that it also implements the Map interface. Thus, Hashtable is now integrated into the collections framework. It is similar to HashMap, but is synchronized.

Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

A hash table can only store objects that override the hashCode() and equals() methods that are defined by Object. The hashCode() method must compute and return the hash code for the object. Of course, equals() compares two objects. Fortunately, many of Java's built-in classes already implement the hashCode() method. For example, the most common type of Hashtable uses a String object as the key. String implements both hashCode() and equals().

The Hashtable constructors are shown here:

Hashtable( ) Hashtable(int size) Hashtable(int size, float fillRatio) Hashtable(Map m)

The first version is the default constructor. The second version creates a hash table that has an initial size specified by size. The third version creates a hash table that has an initial size specified by size and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0,

Page 3: Collection Examples

and it determines how full the hash table can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash table multiplied by its fill ratio, the hash table is expanded. If you do not specify a fill ratio, then 0.75 is used. Finally, the fourth version creates a hash table that is initialized with the elements in m. The capacity of the hash table is set to twice the number of elements in m. The default load factor of 0.75 is used. The fourth constructor was added by Java 2.  

The following example uses a Hashtable to store the names of bank depositors and their current balances:

// Demonstrate a Hashtable import java.util.*; class HTDemo { public static void main(String args[]) { Hashtable balance = new Hashtable(); Enumeration names; String str; double bal; balance.put("John Doe", new Double(3434.34)); balance.put("Tom Smith", new Double(123.22)); balance.put("Jane Baker", new Double(1378.00)); balance.put("Todd Hall", new Double(99.22)); balance.put("Ralph Smith", new Double(-19.08)); // Show all balances in hash table. names = balance.keys(); while(names.hasMoreElements()) { str = (String) names.nextElement(); System.out.println(str + ": " + balance.get(str)); } System.out.println(); // Deposit 1,000 into John Doe's account bal = ((Double)balance.get("John Doe")).doubleValue(); balance.put("John Doe", new Double(bal+1000)); System.out.println("John Doe's new balance: " + balance.get("John Doe")); } }

The output from this program is shown here:

Ralph Smith: -19.08 Tom Smith: 123.22 John Doe: 3434.34 Todd Hall: 99.22

Page 4: Collection Examples

Jane Baker: 1378.0 John Doe's new balance: 4434.34

One important point: like the map classes, Hashtable does not directly support iterators. Thus, the preceding program uses an enumeration to display the contents of balance. However, you can obtain set-views of the hash table, which permits the use of iterators. To do so, you simply use one of the collection-view methods defined by Map, such as entrySet( ) or keySet( ). For example, you can obtain a set-view of the keys and iterate through them. Here is a reworked version of the program that shows this technique:

// Use iterators with a Hashtable. import java.util.*; class HTDemo2 { public static void main(String args[]) { Hashtable balance = new Hashtable(); String str; double bal; balance.put("John Doe", new Double(3434.34)); balance.put("Tom Smith", new Double(123.22)); balance.put("Jane Baker", new Double(1378.00)); balance.put("Todd Hall", new Double(99.22)); balance.put("Ralph Smith", new Double(-19.08)); // show all balances in hashtable Set set = balance.keySet(); // get set-view of keys // get iterator Iterator itr = set.iterator(); while(itr.hasNext()) { str = (String) itr.next(); System.out.println(str + ": " + balance.get(str)); } System.out.println(); // Deposit 1,000 into John Doe's account bal = ((Double)balance.get("John Doe")).doubleValue(); balance.put("John Doe", new Double(bal+1000)); System.out.println("John Doe's new balance: " + balance.get("John Doe")); } }

HashMap example in JavaThe HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets. The following constructors are defined:

Page 5: Collection Examples

HashMap( ) HashMap(Map m) HashMap(int capacity) HashMap(int capacity, float fillRatio)

The first form constructs a default hash map. The second form initializes the hash map by using the elements of m. The third form initializes the capacity of the hash map to capacity. The fourth form initializes both the capacity and fill ratio of the hash map by using its arguments. The meaning of capacity and fill ratio is the same as for HashSet, described earlier.

HashMap implements Map and extends AbstractMap. It does not add any methods of its own. You should note that a hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator.

The following program illustrates HashMap. It maps names to account balances. Notice how a set-view is obtained and used.

import java.util.*; class HashMapDemo { public static void main(String args[]) { // Create a hash map HashMap hm = new HashMap(); // Put elements to the map hm.put("John Doe", new Double(3434.34)); hm.put("Tom Smith", new Double(123.22)); hm.put("Jane Baker", new Double(1378.00)); hm.put("Todd Hall", new Double(99.22)); hm.put("Ralph Smith", new Double(-19.08)); // Get a set of the entries Set set = hm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); // Deposit 1000 into John Doe's account double balance = ((Double)hm.get("John Doe")).doubleValue(); hm.put("John Doe", new Double(balance + 1000)); System.out.println("John Doe's new balance: " + hm.get("John Doe"));

Page 6: Collection Examples

} }

Output from this program is shown here:

Ralph Smith: -19.08 Tom Smith: 123.22 John Doe: 3434.34 Todd Hall: 99.22 Jane Baker: 1378.0 John Doe's current balance: 4434.34

The program begins by creating a hash map and then adds the mapping of names to balances. Next, the contents of the map are displayed by using a set-view, obtained by calling entrySet(). The keys and values are displayed by calling the getKey() and getValue() methods that are defined by Map.Entry. Pay close attention to how the deposit is made into John Doe's account. The put() method automatically replaces any preexisting value that is associated with the specified key with the new value. Thus, after John Doe's account is updated, the hash map will still contain just one "John Doe" account.

Java – Map ExampleMap interface is part of java.util package. Map interface can add key and value put(key, value) pair elements. This Map permits null value. Map is interface. Key and value of Map can get by Set Interface and Map interface through Iterator interface.

Map example give a method, how to use Map in java.

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

public class MapExample {

public static void main(String[] args) {

Map<Object,String> mp=new HashMap<Object, String>();

// adding or set elements in Map by put method key and value pair mp.put(new Integer(2), "Two"); mp.put(new Integer(1), "One"); mp.put(new Integer(3), "Three"); mp.put(new Integer(4), "Four");

//Get Map in Set interface to get key and value Set s=mp.entrySet();

Page 7: Collection Examples

//Move next key and value of Map by iterator Iterator it=s.iterator();

while(it.hasNext()) { // key=value separator this by Map.Entry to get key and value Map.Entry m =(Map.Entry)it.next();

// getKey is used to get key of Map int key=(Integer)m.getKey();

// getValue is used to get value of key in Map String value=(String)m.getValue();

System.out.println("Key :"+key+" Value :"+value); } }}

Output

Key :1 Value :OneKey :2 Value :TwoKey :3 Value :ThreeKey :4 Value :Four

Java – HashMap ExampleHashMap class is part of java.util package. HashMap class can add key and value put(key, value) pair elements. This HashMap permits null key and value. But HashMap is unsynchronized. HashMap class gives no guarantee to return as original order as entered.HashMap extends AbstractMap class and implements Map interface. Key and value of HashMap can get by Set Interface and Map interface through Iterator interface.

HashMap example give a method, how to use HashMap in java.

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

public class HashMapExample {

public static void main(String[] args) {

HashMap<Object,String> hm=new HashMap<Object,String>();

// adding or set elements in HashMap by put method key and value pair hm.put(new Integer(2), "Two"); hm.put(new Integer(1), "One");

Page 8: Collection Examples

hm.put(new Integer(3), "Three"); hm.put(new Integer(4), "Four");

// Get hashmap in Set interface to get key and value Set s=hm.entrySet();

// Move next key and value of HashMap by iterator Iterator it=s.iterator();

while(it.hasNext()) { // key=value separator this by Map.Entry to get key and value Map.Entry m =(Map.Entry)it.next();

// getKey is used to get key of HashMap int key=(Integer)m.getKey();

// getValue is used to get value of key in HashMap String value=(String)m.getValue();

System.out.println("Key :"+key); System.out.println("value :"+value); } }}

Output

Key :1value :OneKey :2value :TwoKey :3value :ThreeKey :4value :Four

Java – Hashtable ExampleHashtable class is part of java.util package. Hashtable class can add key and value put(key, value) pair elements. Hashtable do not permit null key and value. But Hashtable is synchronized. Hashtable class return ordered entry as entered.Hashtable extends Dictionary class and implements Map interface. Key and value of Hashtable can get by Set Interface and Map interface through Iterator and Enumeration interface.

Hashtable example give a method, how to use Hashtable in java

1. Hashtable example with Enumeration

import java.util.Hashtable;

Page 9: Collection Examples

import java.util.Enumeration;

public class HashTableExample {

public static void main(String[] args) {

Hashtable<Integer,String> hTable=new Hashtable<Integer,String>();

//adding or set items in Hashtable by put method key and value pair hTable.put(new Integer(2), "Two"); hTable.put(new Integer(1), "One"); hTable.put(new Integer(4), "Four"); hTable.put(new Integer(3), "Three"); hTable.put(new Integer(5), "Five");

// Get Hashtable Enumeration to get key and value Enumeration em=hTable.keys();

while(em.hasMoreElements()) { //nextElement is used to get key of Hashtable int key = (Integer)em.nextElement();

//get is used to get value of key in Hashtable String value=(String)hTable.get(key);

System.out.println("Key :"+key+" value :"+value); } }}

2. Hashtable example with Enumeration

import java.util.Hashtable;import java.util.Iterator;import java.util.Set;import java.util.Map;

public class HashTableJava {

public static void main(String[] args) {

Hashtable<Integer,String> hTable=new Hashtable<Integer,String>();

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

Set s =hTable.entrySet();

Iterator i=s.iterator();

while(i.hasNext()) {

Page 10: Collection Examples

Map.Entry m=(Map.Entry)i.next();

int key = (Integer)m.getKey(); String value=(String)m.getValue();

System.out.println("Key :"+key+" value :"+value); } }}

Output

Key :5 value :FiveKey :4 value :FourKey :3 value :ThreeKey :2 value :TwoKey :1 value :One

Java – Remove elements in MapElement in Map can be removed by remove() method. In remove method, we can pass object to remove.

map.remove(object);

Example of removing element in Map

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

public class MapRemoveExample {

public static void main(String[] args) {

Map<Object,String> mp=new HashMap<Object, String>();

mp.put(new Integer(2), "Two"); mp.put(new Integer(1), "One"); mp.put(new Integer(3), "Three"); mp.put(new Integer(4), "Four");

// remove map object mp.remove(new Integer(3)); // remove map by object

Set s=mp.entrySet();

Iterator it=s.iterator();

while(it.hasNext()) {

Page 11: Collection Examples

Map.Entry m =(Map.Entry)it.next();

int key=(Integer)m.getKey();

String value=(String)m.getValue();

System.out.println("Key :"+key+" Value :"+value); } }}

Java – Iterator ExampleIterator example in java will explain how to use Iterator with collections. Iterator is interface and found in java.util package.

Iterator example give a method, how to use Iterator in java.

import java.util.Hashtable;import java.util.Iterator;import java.util.Set;import java.util.Map;

public class IteratorExample {

public static void main(String[] args) {

Hashtable<Integer,String> hTable=new Hashtable<Integer,String>();

hTable.put(new Integer(2), "Two"); hTable.put(new Integer(1), "One"); hTable.put(new Integer(4), "Four"); hTable.put(new Integer(3), "Three");

Set s =hTable.entrySet();

// Using iterator in hashtable Iterator i=s.iterator();

while(i.hasNext()) { Map.Entry m=(Map.Entry)i.next();

int key = (Integer)m.getKey(); String value=(String)m.getValue();

System.out.println("Key :"+key+" value :"+value); } }}

Output

Page 12: Collection Examples

Key :4 value :FourKey :3 value :ThreeKey :2 value :TwoKey :1 value :One

Java – List ExampleList interface is part of java.util package. List interface can add value elements by add(value) method.List can implement Vector, ArrayList class.List value can get by Iterator interface.

List example give a method, how to use List in java.

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

public class ListExample {

public static void main(String[] args) {

// List Example implement with ArrayList List<String> ls=new ArrayList<String>();

ls.add("one"); ls.add("Three"); ls.add("two"); ls.add("four");

Iterator it=ls.iterator();

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

System.out.println("Value :"+value); } }}

Output

List Value neList Value :ThreeList Value :twoList Value :four

Page 13: Collection Examples

Java – Remove elements in ListElement in List can be removed by remove() method. In remove method, we can pass object to remove.

list.remove(object);

Example of removing element in List

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

public class ListRemoveExample {

public static void main(String[] args) {

List<String> ls=new ArrayList<String>();

ls.add("one"); ls.add("Three"); ls.add("two"); ls.add("four");

// remove list object ls.remove(2); // remove by index number

ls.remove("four"); // remove by object

Iterator it=ls.iterator();

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

System.out.println("Value :"+value); } }}

Java – How to clear listAll Elements in List can be removed by clear() method. Clear() method in List clear List object and size of the List will become 0

Example of clear in List

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

Page 14: Collection Examples

public class ListClearExample {

public static void main(String[] args) {

List<String> ls=new ArrayList<String>();

ls.add("one"); ls.add("Three"); ls.add("two"); ls.add("four");

ls.clear(); // clear all elements from list collection

System.out.println("Size of list after clear :"+ls.size()); }}

Output

Size of list after clear :0

Java – How to get size of ListSize of List can be find by size() method. In size method, it will return value in integer.

Example of finding size in List in Java

List<String> ls=new ArrayList<String>();

ls.add("one");ls.add("Three");ls.add("two");ls.add("four");

int sizeOfList=ls.size();

System.out.println("Size of List :"+sizeOfList);

Output

Size of List :4

Java – Scheduling task with Timer classIf you want to execute some task repeat at fix interval, Time class help you to achieve it.

Timer can do scheduling with fix interval with delay and allow defining in milliseconds.

Page 15: Collection Examples

Timer TimerTask implement with run() interface of multi threading.

1. timer.schedule(new TimerTask(),1000); run one time after 1 second 2. timer.schedule(new TimerTask(),1000,1000); start after one 1 second and repeat every

1 second infinitely

The example will run statement after 10 second and run every 1 second

import java.util.Timer;import java.util.TimerTask;

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

Timer timer= new Timer();

int startingTime=10000; //millisecond 10 seconds=10000 int delayTime=1000; // millisecond 1 second timer.schedule(new TimerTask() { public void run() { System.out.println("Timer repeat statement"); } },startingTime,delayTime);

}}

Java – How to get size of VectorSize of Vector can be find by size() method. In size method, it will return value in integer.

Example of finding size in Vector in Java

Vector vc=new Vector();

vc.add("a");vc.add("b");vc.add("c");

int size = vc.size();

System.out.println("Size of vector in java :"+size);

Output

Size of vector in java :3

Page 16: Collection Examples

Java – Vector ExampleVector class is in java.util package of java. Vector is dynamic array which can grow automatically according to the required need. Vector does not require any fix dimension like String array and int array. Vector contains many useful methods. To add element in Vector, we can use add() method of vector class. To add elements at fix position, we have to use add(index, object) method.

To get value from Vector, Vector provides get() method and Vector size() method. Size() method returns total number of elements in Vector.

Vector is synchronized, ArrayList is not

Vector Example

import java.util.Vector;

public class VectorExample {

public static void main(String[] args) {

Vector<String> vc=new Vector<String>();

// <E> Element type of Vector e.g. String, Integer, Object ...

// add vector elements vc.add("Vector Object 1"); vc.add("Vector Object 2"); vc.add("Vector Object 3"); vc.add("Vector Object 4"); vc.add("Vector Object 5");

// add vector element at index vc.add(3, "Element at fix position");

// vc.size() inform number of elements in Vector System.out.println("Vector Size :"+vc.size());

// get elements of Vector for(int i=0;i<vc.size();i++) { System.out.println("Vector Element "+i+" :"+vc.get(i)); } }}

Java – Default Capacity of VectorFind default capacity of Vector in JAVA

Page 17: Collection Examples

In this example, We will find default capacity of vector in collections in java.

import java.util.Vector;public class VectorSize {

public static void main(String[] args) {

Vector vc=new Vector();

System.out.println("Default Capacity of Vector is :"+vc.capacity());

vc.add("first element");

System.out.println("Default Capacity of Vector after one element :"+vc.capacity());

vc.add("second element");

System.out.println("Default Capacity of Vector after two elements :"+vc.capacity());

}}

Output

Default Capacity of Vector is :10Default Capacity of Vector after one element :10Default Capacity of Vector after two elements :10

Java – Remove elements in VectorElement in Vector can be removed by remove() method. In remove method, we can pass object or index number to remove.

Example of removing element in Vector

import java.util.Vector;

public class RemoveVectorElement {

public static void main(String[] args) {

Vector<String> vc=new Vector<String>();

//<E> it is return type of Vector

// add vector elements vc.add("Vector Element 1"); vc.add("Vector Element 2"); vc.add("Vector Element 3"); vc.add("Vector Element 4");

Page 18: Collection Examples

vc.add("Vector Element 5");

// remove Vector element by index number vc.remove(3);

// remove Vector element by Object value vc.remove("Vector Element 5");

// get elements of Vector for(int i=0;i<vc.size();i++) { System.out.println("Vector Element "+i+" :"+vc.get(i)); } }}

output

Vector Element 0 :Vector Element 1Vector Element 1 :Vector Element 2Vector Element 2 :Vector Element 3

Java – StringBuffer capacity() Example, StringBuffer capacity() programStringBuffer capacity can be found with the help of capacity() method in java. capacity() function find current storage of characters. Return type of capacity() is integer. Use of String capacity() in java is shown below.

Example of StringBuffer capacity() in java, JSP

public class StringBufferCapacityExample {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Java StringBuffer capacity");

System.out.println("Output :"+sb);

int lg = sb.length();

int lng = sb.capacity();

System.out.println("length :"+lg); System.out.println("capacity :"+lng); }}

Output

Page 19: Collection Examples

Output :Java StringBuffer capacitylength :26capacity :42

Java – How to Clear VectorAll Elements in Vector can be removed by clear() method. Clear() method in Vector clear Vector object and size of the Vector will become 0

Example of clear in Vector

import java.util.Vector;

public class VectorClearExample {

public static void main(String[] args) {

Vector<String> vc=new Vector<String>();

vc.add("Vector Element 1"); vc.add("Vector Element 2"); vc.add("Vector Element 3");

vc.clear(); // clear all elements from Vector

System.out.println("Vector Size :"+vc.size()); }}

Output

Vector Size :0

Java – StringBuffer Example, StringBuffer programStringBuffer is mutable sequence of characters. It can store character, append character, delete character easily. StringBuffer is a thread safe sequence of characters, and it is synchronized. StringBuffer is like a normal String but it can modify at any point. StringBuffer can easily use in multi thread programs. Use of StringBuffer in java is shown below.

Example of StringBuffer in java, JSP

public class StringBufferExample {

public static void main(String[] args) {

Page 20: Collection Examples

StringBuffer sb = new StringBuffer();

sb.append("Java StringBuffer");

System.out.println("Output :"+sb); }}

Output

Output :Java StringBuffer

Java – StringBuffer Append() Example, StringBuffer Append() programStringBuffer character sequence can be appended with the help of append() method in java. append() function appends characters in the end of previous character sequence of the String. StringBuffer append is fastest way to append String. Use of String append() in java is shown below.

Example of StringBuffer append() in java, JSP

public class StringBufferAppendExample {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer();

sb.append("Java StringBuffer");

System.out.println("Output1 :"+sb);

sb.append("Append StringBuffer");

System.out.println("Output2 :"+sb); }}

Output

Output1 :Java StringBufferOutput2 :Java StringBufferAppend StringBuffer

Java – ArrayList ExampleArrayList class is in java.util package of java. ArrayList is dynamic array which can grow automatically according to the required need. ArrayList does not require any fix dimension like

Page 21: Collection Examples

String array and int array. ArrayList contains many useful methods. To add element in ArrayList, we can use add() method of ArrayList class. To add elements at fix position, we have to use add(index, object) method.

To get value from ArrayList, ArrayList provides get() method and ArrayList size() method. Size() method returns total number of elements in ArrayList.

Example of ArrayList in java

import java.util.ArrayList;

public class ArrayListExample {

public static void main(String[] args) {

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

//<E> it is return type of ArrayList

arlist.add("First Element"); // adding element in ArrayList arlist.add("Second Element"); arlist.add("Third Element"); arlist.add("forth Element"); arlist.add("fifth Element");

// add element with index for fix order

arlist.add(2, "Fixed Order of Element");

// arlist.size() inform number of elements in ArrayList System.out.println("ArrayList Size :"+arlist.size());

// get elements of ArrayList for(int i=0;i<arlist.size();i++) { System.out.println("ArrayList Element "+i+" :"+arlist.get(i)); } }}

output

ArrayList Size :6ArrayList Element 0 :First ElementArrayList Element 1 :Second ElementArrayList Element 2 :Fixed Order of ElementArrayList Element 3 :Third ElementArrayList Element 4 :forth ElementArrayList Element 5 :fifth Element

Java ArrayList

Page 22: Collection Examples

ArrayList arlist=new ArrayList();

arlist.add("1 Arraylist"); // adding element in ArrayList arlist.add("2 Arraylist"); arlist.add("3 Arraylist"); arlist.add("4 Arraylist"); arlist.add("5 Arraylist");

System.out.println("ArrayList Size :"+arlist.size());

// Display ArrayList for(int i=0;i<arlist.size();i++) { System.out.println("ArrayList "+i+" :"+arlist.get(i)); }

Java – How to get size of ArrayListSize of ArrayList can be find by size() method. In size method, it will return value in integer.

Example of finding size in ArrayList in Java

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

arlist.add("First Element");arlist.add("Second Element");arlist.add("Third Element");arlist.add("forth Element");arlist.add("fifth Element");

int sizeOfArrayList=arlist.size();

System.out.println("Size of ArrayList :"+sizeOfArrayList);

Output

Size of ArrayList :5

Java – Remove Element in ArrayListElement in ArrayList can be removed by remove() method. In remove method, we can pass object or index number to remove.

Example of removing element in Arraylist

import java.util.ArrayList;

public class RemoveArrayListElement {

public static void main(String[] args) {

Page 23: Collection Examples

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

//<E> it is return type of ArrayList

arlist.add("First Element"); // adding element in ArrayList arlist.add("Second Element"); arlist.add("Third Element"); arlist.add("forth Element"); arlist.add("fifth Element");

// remove array list element by index number arlist.remove(3);

// remove ArrayList element by Object value arlist.remove("fifth Element");

// get elements of ArrayList for(int i=0;i<arlist.size();i++) { System.out.println("ArrayList Element "+i+" :"+arlist.get(i)); } }}

Output

Remove ArrayList Element 0 :First ElementRemove ArrayList Element 1 :Second ElementRemove ArrayList Element 2 :Third Element

Java – Remove Element in ArrayListElement in ArrayList can be removed by remove() method. In remove method, we can pass object or index number to remove.

Example of removing element in Arraylist

import java.util.ArrayList;

public class RemoveArrayListElement {

public static void main(String[] args) {

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

//<E> it is return type of ArrayList

arlist.add("First Element"); // adding element in ArrayList arlist.add("Second Element"); arlist.add("Third Element"); arlist.add("forth Element");

Page 24: Collection Examples

arlist.add("fifth Element");

// remove array list element by index number arlist.remove(3);

// remove ArrayList element by Object value arlist.remove("fifth Element");

// get elements of ArrayList for(int i=0;i<arlist.size();i++) { System.out.println("ArrayList Element "+i+" :"+arlist.get(i)); } }}

Output

Remove ArrayList Element 0 :First ElementRemove ArrayList Element 1 :Second ElementRemove ArrayList Element 2 :Third Element

Java – Set ExampleSet interface is part of java.util package. Set interface can add value elements by add(value) method.Set can implement TreeSet class.Set value can get by Iterator interface.

Set example give a method, how to use Set in java.

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

public class SetExample {

public static void main(String[] args) {

// Set example with implement TreeSet Set<String> s=new TreeSet<String>();

s.add("b"); s.add("a"); s.add("d"); s.add("c");

Iterator it=s.iterator();

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

Page 25: Collection Examples

System.out.println("Value :"+value); } }}

Output

Set Value :aSet Value :bSet Value :cSet Value :d

Java – TreeSet ExampleTreeSet class is part of java.util package. TreeSet class can add value elements by add(value) method.TreeSet value can get by Iterator interface.

TreeSet example give a method, how to use TreeSet in java.

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

public class TreeSetExample {

public static void main(String[] args) {

// TreeSet return in ordered elements TreeSet<String> ts=new TreeSet<String>();

ts.add("b"); ts.add("a"); ts.add("d"); ts.add("c");

// get element in Iterator Iterator it=ts.iterator();

// get descending order of elements //Iterator it=ts.descendingIterator();

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

System.out.println("Value :"+value); } }}

Page 26: Collection Examples

Output

TreeSet Value :aTreeSet Value :bTreeSet Value :cTreeSet Value :d

Java – SortedSet ExampleSortedSet interface is part of java.util package. SortedSet interface can add value add(value) elements. Value of SortedSet can get by Iterator Interface.

SortedSet example give a method, how to use SortedSet in java.

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

public class SortedSetExample {

public static void main(String[] args) {

SortedSet<String> ss=new TreeSet<String>();

ss.add("a"); ss.add("e"); ss.add("g"); ss.add("b"); ss.add("c");

Iterator it=ss.iterator();

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

System.out.println("Value :"+value); } }}

Output

Value :aValue :bValue :cValue :eValue :g

Page 27: Collection Examples

Java – Remove elements in TreeSetElement in TreeSet can be removed by remove() method. In remove method, we can pass object to remove.

treeSet.remove(object);

Example of removing element in TreeSet

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

public class TreeSetRemoveExample {

public static void main(String[] args) {

TreeSet<String> ts=new TreeSet<String>();

ts.add("b"); ts.add("a"); ts.add("d"); ts.add("c");

// TreeSet remove object ts.remove("d");

Iterator it=ts.iterator();

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

System.out.println("Value :"+value); } }}

Java – SortedMap ExampleSortedMap interface is part of java.util package. SortedMap interface can add key and value put(key, value) pair elements. This SortedMap permits null value. Key and value of SortedMap can get by Set Interface and Map interface through Iterator interface.

SortedMap example give a method, how to use SortedMap in java.

import java.util.Iterator;import java.util.Map;import java.util.Set;import java.util.SortedMap;import java.util.TreeMap;

Page 28: Collection Examples

public class SortedMapExample {

public static void main(String[] args) {

SortedMap<Integer,String> sm=new TreeMap<Integer, String>();

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

Set s=sm.entrySet();

// Using iterator in SortedMap Iterator i=s.iterator();

while(i.hasNext()) { Map.Entry m =(Map.Entry)i.next();

int key = (Integer)m.getKey(); String value=(String)m.getValue();

System.out.println("Key :"+key+" value :"+value); } }}

Output

Key :1 value :OneKey :2 value :TwoKey :3 value :ThreeKey :4 value :FourKey :5 value :Five

Java – List ExampleList interface is part of java.util package. List interface can add value elements by add(value) method.List can implement Vector, ArrayList class.List value can get by Iterator interface.

List example give a method, how to use List in java.

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

Page 29: Collection Examples

public class ListExample {

public static void main(String[] args) {

// List Example implement with ArrayList List<String> ls=new ArrayList<String>();

ls.add("one"); ls.add("Three"); ls.add("two"); ls.add("four");

Iterator it=ls.iterator();

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

System.out.println("Value :"+value); } }}

Output

List Value neList Value :ThreeList Value :twoList Value :four


Recommended