Java @ Desk: Java Collection | Java at your desk

Difference between fail-fast and fail-safe

Difference between fail-fast and fail-safe

fail-fast and fail-safe are related to java.util.Iterator class in Java.

Iterator fail-fast states that, it should throw the exception ConcurrentModificationException if the collection is modified during the iteration. All the collection in java.util package are by default fail-fast in nature.

The exception is thrown as shown below
while(iterator.hasNext()) {
 iterator.next(); // It will throw ConcurrentModificationException once it reach here after adding an   element in the list
 sharedQueue.add(10);
}

As shown above, next() throws the ConcurrentModificationException if the element is added in the list while iteration.

Iterator fail-safe states that, it will not throw ConcurrentModificationException even though the collection gets modified. Classes in the package java.util.concurrent are fail-safe. ConcurrentHashMap and CopyOnWriteArrayList are fail-safe because the iterator does not throws any exception while the collection gets modified. Click here for implementation of CopyOnWriteArrayList.

Difference between WeakHashMap vs HashMap

WeakHashMap in Java with example

WeakHashMap in java is an implementation of Map interface.

Reference in java are memory address where the created objects points in the memory. In a WeakHashMap, concept of Weak Reference is used.

As soon as you create an object in java and assign it to some variable, it becomes strongly reachable.

Weak reference object can somewhat be similar to object that has no memory references i.e. it can be garbage collected now.

Difference between WeakHashMap vs HashMap

In other Map implementations like a HashMap, the keys are strongly reachable. For example, if a HashMap has keys as Person class as shown below and if Person object is set to null, even after this if we will do map.get(Person) we will get the value from the memory since the keys are strongly referenced in a HashMap.

wm.put(person, person.getFirstName());
person = null;
System.gc();
System.out.println("Hash Map :" + wm.toString());

Output : Hash Map :{test.Person@12dacd1=John}

Compared to HashMap, WeakHashMap is the one which will remove its enteries as soon as the keys have no reference in the memory. For example, if a WeakHashMap has keys as Person class as shown below and if Person object is set to null, now if you do map.get(Person) we will get null out of it because the key has no reference (or rather weakly reachable).
wm.put(person, person.getFirstName());
person = null;
System.gc();
System.out.println("Weak Hash Map :" + wm.toString());

Output : Weak Hash Map :{}


Map<Person, String> wm = new WeakHashMap<Person, String>();
Person person = new Person();
person.setAge(25);
person.setFirstName("John");
wm.put(person, person.getFirstName());
  
Person person2 = new Person();
person2.setAge(35);
person2.setFirstName("Anderson");
wm.put(person2, person2.getFirstName());

System.gc();
System.out.println("Weak Hash Map :" + wm.toString());

person = null;
System.gc();
System.out.println("Weak Hash Map :" + wm.toString());


Running the above code gives us

Weak Hash Map :{test.Person@42719c=Anderson, test.Person@10385c1=John}
Weak Hash Map :{test.Person@42719c=Anderson}

Before nullifying the person object, WeakHashMap consists of both the enteries. Once the person object is nullified, garbage collector removed the object from the memory and since it is weakly referenced, WeakHashMap removed the entry for key person



String as a key for WeakHashMap

String is not suitable for WeakHashMap if used as a key. This is because, when a String object is created JVM creates the object in the String pool also. They may remain strongly referenced in the string pool even after you have nullified the reference.
Map<String, String> stringWeakHashMap = new WeakHashMap<String, String>();
String str1 = "Key 1";
String str2 = "Key 2";
  
stringWeakHashMap.put(str1, "Value 1");
stringWeakHashMap.put(str2, "Value 2");
str1 = null;
  
System.gc();
System.out.println("Weak Hash Map :" + stringWeakHashMap.toString());

After running the above code the output generated is

Weak Hash Map :{Key 2=Value 2, Key 1=Value 1}


It is clearly visible, since the string objects have strong reference due to string pool the key "str1" is not removed from the WeakHashMap

Find Minimum Date From ArrayList In Java






Find Minimum Date From ArrayList In Java

There are two ways to get maximum Date from an ArrayList:

1) Collections.min() from java.util.Collections
3) Using Collections.sort() from java.util.Collections

Sample Implementation:

package test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class FindMinimumDateArrayList {

 public static void main(String args[]) throws ParseException {
  List<Date> dates = new ArrayList<Date>();

  SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
  Date date = fmt.parse("2013-07-06");
  Date dateOne = fmt.parse("2017-05-06");
  Date dateTwo = fmt.parse("2001-01-06");

  dates.add(date);
  dates.add(dateOne);
  dates.add(dateTwo);

  // Using java.util.Collections
  System.out.println("Minimum Element : "
    + fmt.format(Collections.min(dates)));

  // // Using Sort Technique of java.util.Collections
  Collections.sort(dates);
  System.out.println("Minimum Element After Sorting - "
    + fmt.format(dates.get(0)));

 }
}

Find Maximum Date From ArrayList In Java






Find Maximum Date From ArrayList In Java

There are two ways to get maximum Date from an ArrayList:

1) Collections.max() from java.util.Collections
3) Using Collections.sort() from java.util.Collections

Sample Implementation:

package test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class FindMaxDateArrayList {

 public static void main(String args[]) throws ParseException {
  List<Date> dates = new ArrayList<Date>();

  SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
  Date date = fmt.parse("2013-07-06");
  Date dateOne = fmt.parse("2017-05-06");
  Date dateTwo = fmt.parse("2001-01-06");

  dates.add(date);
  dates.add(dateOne);
  dates.add(dateTwo);

  // Using java.util.Collections
  System.out.println("Maximum Element : "
    + fmt.format(Collections.max(dates)));

  // // Using Sort Technique of java.util.Collections
  Collections.sort(dates);
  System.out.println("Maximum Element After Sorting - "
    + fmt.format(dates.get(dates.size() - 1)));

 }
}

HashMap vs TreeMap vs LinkedHashMap in Java

HashMap vs TreeMap vs LinkedHashMap in Java

java.util.HashMap, java.util.LinkedHashMap, java.util.TreeMap implements the Map interface in Java. All 3 implementation fulfill the basic principal of a Map interface by not allowing duplicates keys. The put() method returns a boolean. In case of duplicate entry, the add() method returns false.

Difference between the three :

1) Sorting and Ordering of Elements

HashMap does not maintains any order of elements. Every time a new element is added, the order of elements may or may not be changed. LinkedHashMap strictly maintains inserion order of elements. TreeSet also does not maintains insertion order, it sorts the element and maintain sorting order

HashMap -> Does not maintain insertion order
LinkedHashMap -> Maintains insertion order
TreeMap -> Does not maintain insertion order as it sorts the elements inserted based on keys.

2) Null Elements
HashMap -> Allow 1 Null Key
LinkedHashMap -> Allow 1 Null Key
TreeMap -> Does not Allow Null Key. Throws RuntimeException (NullPointerException).

WeakHashMap in Java with example

WeakHashMap in Java with example

WeakHashMap in java is an implementation of Map interface.

Reference in java are memory address where the created objects points in the memory. In a WeakHashMap, concept of Weak Reference is used.

As soon as you create an object in java and assign it to some variable, it becomes strongly reachable.

Weak reference object can somewhat be similar to object that has no memory references i.e. it can be garbage collected now.

Difference between WeakHashMap vs HashMap

In other Map implementations like a HashMap, the keys are strongly reachable. For example, if a HashMap has keys as Person class as shown below and if Person object is set to null, even after this if we will do map.get(Person) we will get the value from the memory since the keys are strongly referenced in a HashMap.

wm.put(person, person.getFirstName());
person = null;
System.gc();
System.out.println("Hash Map :" + wm.toString());

Output : Hash Map :{test.Person@12dacd1=John}

Compared to HashMap, WeakHashMap is the one which will remove its enteries as soon as the keys have no reference in the memory. For example, if a WeakHashMap has keys as Person class as shown below and if Person object is set to null, now if you do map.get(Person) we will get null out of it because the key has no reference (or rather weakly reachable).
wm.put(person, person.getFirstName());
person = null;
System.gc();
System.out.println("Weak Hash Map :" + wm.toString());

Output : Weak Hash Map :{}


Map<Person, String> wm = new WeakHashMap<Person, String>();
Person person = new Person();
person.setAge(25);
person.setFirstName("John");
wm.put(person, person.getFirstName());
  
Person person2 = new Person();
person2.setAge(35);
person2.setFirstName("Anderson");
wm.put(person2, person2.getFirstName());

System.gc();
System.out.println("Weak Hash Map :" + wm.toString());

person = null;
System.gc();
System.out.println("Weak Hash Map :" + wm.toString());


Running the above code gives us

Weak Hash Map :{test.Person@42719c=Anderson, test.Person@10385c1=John}
Weak Hash Map :{test.Person@42719c=Anderson}

Before nullifying the person object, WeakHashMap consists of both the enteries. Once the person object is nullified, garbage collector removed the object from the memory and since it is weakly referenced, WeakHashMap removed the entry for key person



String as a key for WeakHashMap

String is not suitable for WeakHashMap if used as a key. This is because, when a String object is created JVM creates the object in the String pool also. They may remain strongly referenced in the string pool even after you have nullified the reference.
Map<String, String> stringWeakHashMap = new WeakHashMap<String, String>();
String str1 = "Key 1";
String str2 = "Key 2";
  
stringWeakHashMap.put(str1, "Value 1");
stringWeakHashMap.put(str2, "Value 2");
str1 = null;
  
System.gc();
System.out.println("Weak Hash Map :" + stringWeakHashMap.toString());

After running the above code the output generated is

Weak Hash Map :{Key 2=Value 2, Key 1=Value 1}


It is clearly visible, since the string objects have strong reference due to string pool the key "str1" is not removed from the WeakHashMap

HashSet vs TreeSet vs LinkedHashSet in Java

HashSet vs TreeSet vs LinkedHashSet in Java

java.util.HashSet, java.util.LinkedHashSet, java.util.TreeSet implements the Set interface in Java. All 3 implementation fulfill the basic principal of a Set interface by not allowing duplicates enteries. The add() method returns a boolean. In case of duplicate entry, the add() method returns false.

Difference between the three :

1) How duplicates are detected internally while adding an element

When add() method is called among the three internally, HashSet and LinkedHashSet uses the .equals() to compare if the object is present or not. If the element is present .equals() method returns true and the element is not added.

But TreeSet uses .compareTo(). If the method returns 0, the element is present and it is not added. If it returns -1 or +1, it performs the sorting of elements.

2) Sorting and Ordering of Elements

HashSet does not maintains any order of elements. Every time a new element is added, the order of elements may or may not be changed. LinkedHashSet strictly maintains inserion order of elements. TreeSet also does not maintains insertion order, it sorts the element and maintain sorting order

HashSet -> Does not maintain insertion order
LinkedHashSet -> Maintains insertion order
TreeSet -> Does not maintain insertion order as it sorts the elements inserted.

3) Null Elements

As discussed in point 1, while adding an element in HashSet or LinkedHashSet .equals() method is used. So it allows null elements insertion.

But in TreeSet, it uses .compareTo(). So when null is inserted .compareTo() method is called on it resulting in NullPointerException

HashSet -> Allow Null
LinkedHashSet -> Allow Null
TreeSet -> Does not Allow Null. Throws RuntimeException (NullPointerException).

4) Performance

TreeSet is slowest because everytime .add() method is called to insert an element it needs to sort the complete Set. If the Set is of 10000 elements, complete sorting will be required.

LinkedHashSet is at second while HashSet is at the top performance wise.

Find Minimum Value From ArrayList In Java



Find Minimum Value From ArrayList In Java

There are three ways to get Minimum value from an ArrayList:

1) Collections.min() from java.util.Collections
2) Using Iteration
3) Using Collections.sort() from java.util.Collections

Click to see Sort ArrayList Using Comparator In Java

Sample Implementation:

package test;

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

public class FindMinIntegerArrayList {

 public static void main(String args[]) {
  List<Integer> integers = new ArrayList<Integer>();

  integers.add(1000);
  integers.add(895);
  integers.add(640);
  integers.add(1089);

  // Using java.util.Collections
  System.out.println("Minimum Element : " + Collections.min(integers));

  // Using Iteration
  Integer min = Integer.MAX_VALUE;
  for (Integer integer : integers) {
   if (integer < min) {
    min = integer;
   }
  }
  System.out.println("Minimum Element after iteration : " + min);

  // Using Sort Technique of java.util.Collections
  Collections.sort(integers);
  System.out.println("Minimum Element After Sorting - "
    + integers.get(0));

 }
}

CopyOnWriteArrayList in Java Example

CopyOnWriteArrayList in Java Example

java.util.ArrayList that implements the List interface is not a thread safe implementation. Also the iterator of an ArrayList is fail-fast i.e. it throws ConcurrentModificationException when the list gets modified while the iterator of ArrayList object is traversing or iterating through the List object.

CopyOnWriteArrayList is an implementation that belongs to concurrent family in a Collection framework. Iterator of CopyOnWriteArrayList is fail-safe, hence it does not throw ConcurrentModificationException when the list gets modified while the iterator of CopyOnWriteArrayList object is traversing or iterating through the List object.

How it works? Why CopyOnWriteArrayList does not throw ConcurrentModificationException Exception?
When the Iterator object is created from the CopyOnWriteArrayList object, it gets the seperate copy of ArrayList on which the Iterator iterates. So even if remove or add operations are performed on the CopyOnWriteArrayList object, the ArrayList of the Iterator does not gets modified.

Difference between CopyOnWriteArrayList and ArrayList in Java.
1) ArrayList is not thread safe whereas CopyOnWriteArrayList is a thread safe collection that is used in concurrent applications

2) ArrayList Iterator throws ConcurrentModificationException when the list gets modified during Iteraion. But CopyOnWriteArrayList does not throw any ConcurrentModificationException even if the list gets modified during Iteraion.

3) CopyOnWriteArrayList does not support remove() functionality whereas ArrayList has remove() method

package test;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

public class CopyOnWriteArrayListExample {
    public static void main(String args[]) {
        final CopyOnWriteArrayList<String> copyOnWriteArrayList = 
            new CopyOnWriteArrayList<String>();
        copyOnWriteArrayList.add("Car Insurance");
        copyOnWriteArrayList.add("Online Accounting Degree");
        copyOnWriteArrayList.add("Insurance");
        copyOnWriteArrayList.add("Personal Loan");
        System.out.println("Original CopyOnWriteArrayList :"
                + copyOnWriteArrayList + "\n");
        // new thread to concurrently modify the list
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                copyOnWriteArrayList.add("Car Loans");
                System.out
                        .println("\nConcurrently the list got modified in another thread");
                System.out.println("New CopyOnWriteArrayList :"
                        + copyOnWriteArrayList + "\n");
            }
        }).start();

        Iterator<String> failSafeIterator = copyOnWriteArrayList.iterator();
        while (failSafeIterator.hasNext()) {
            System.out.printf("Iterating the List - " + failSafeIterator.next()
                    + "\n");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}



As shown in the output below :


1) Original List contains 4 Elements
2) The Iterator object got created on the original list before any modification, so Iterator also contains 4 Elements
3) In between the Iteration, CopyOnWriteArrayList added one element in new thread and the CopyOnWriteArrayList now contains 5 elements
4) But the iterator only displayed 4 elements because Iterator operates on different object of CopyOnWriteArrayList i.e. copy of an CopyOnWriteArrayList object.

Original CopyOnWriteArrayList :[Car Insurance, Online Accounting Degree, Insurance, Personal Loan]

Iterating the List - Car Insurance
Iterating the List - Online Accounting Degree
Iterating the List - Insurance

Concurrently the list got modified in another thread
New CopyOnWriteArrayList :[Car Insurance, Online Accounting Degree, Insurance, Personal Loan, Car Loans]
Iterating the List - Personal Loan

Java Collections - NavigableMap in Java

Java Collections - NavigableMap in Java

java.util.NavigableMap is an interface in java which is being implemented by java.util.TreeMap

TreeMap is a sorted map using the keys of the collection.

So if you are using a TreeMap in your application, following value can be easily achieved with a method calls:
1) Last Key
2) First Key
3) Descending Map
4) Descending Key Set
5) Head Map
6) Tail Map
7) Sub Map
8) Ceiling Key
9) Floor Key
10) Higher Key
11) Lower Key
12) Ceiling Entry, Floor Entry, Higher Entry, Lower Entry
13) Poll First Entry
14) Poll Last Entry

1) Last Key - This returns the last key from the Navigable Map

2) First Key - This returns the first key from the Navigable Map

3) Descending Map - This returns the map object where the keys are in descending order

4) Descending Key Set - This returns the NavigableSet object of keys in descending order

5) Head Map - This returns the Map object that will include all the keys strictly less than the key passed to the method. If true is passed along with the key in a method, the key will also be included in the map returned

6) Tail Map - This returns the Map object that will include current key plus all the keys greater than the key passed to the method. If false is passed along with the key in a method, the passed key will not be included in the map returned

7) Sub Map - This returns a map object in the range. The range includes the keys from fromKey till the key less the toKey passed in the method call. If method with boolean parameter is used and if both the boolean passed are false, then fromKey and toKey will be excluded from the map returned

8) Ceiling Key - This returns the key from the map which is either equal to or greater than the key passed to the method

9) Floor Key - This returns the key from the map which is either equal to or less than the key passed to the method

10) Higher Key - This returns the key from the map which is greater than the key passed to the method

11) Lower Key - This returns the key from the map which is less than the key passed to the method

12) Ceiling Entry, Floor Entry, Higher Entry, Lower Entry - This works the same way as above 4 points. The only difference is, it returns the Map.Entry object instead of a key

13) Poll First Entry - This returns and removes the Map.Entry object of the first entry from Navigable Map. It returns NULL if the map is empty

14) Poll Last Entry - This returns and removes the Map.Entry object of the last entry from Navigable Map. It returns NULL if the map is empty

import java.util.NavigableMap;
import java.util.TreeMap;

public class Testing {

 public static void main(String args[]) throws InterruptedException {
  NavigableMap<String, Integer> navigableMap = new TreeMap<String, Integer>();
  navigableMap.put("Larsen", 2);
  navigableMap.put("Adani", 10);
  navigableMap.put("Reliance", 10);
  navigableMap.put("Tata Motors", 10);
  navigableMap.put("Mahindra", 10);
  navigableMap.put("Birla", 10);
  
  System.out.println("Last Key - "+navigableMap.lastKey());
  System.out.println("First Key - "+navigableMap.firstKey());
  System.out.println("Descending Key Set - " + navigableMap.descendingKeySet());
  System.out.println("Navigable Key Set - " + navigableMap.navigableKeySet());
  
  System.out.println("Descending Map - " + navigableMap.descendingMap());
  System.out.println("Head Map - " + navigableMap.headMap("Reliance"));
  System.out.println("Head Map Including Key Passed - " + navigableMap.headMap("Reliance", true));
  
  System.out.println("Tail Map Including Key Passed - " + navigableMap.tailMap("Reliance"));
  System.out.println("Tail Map Without Key Passed - " + navigableMap.tailMap("Reliance", false));
  
  System.out.println("Sub Map Including toKey - " + navigableMap.subMap("Larsen", "Tata Motors"));
  System.out.println("Sub Map without toKey and fromKey - " + navigableMap.subMap("Larsen", false, "Tata Motors", false));
  
  System.out.println("Ceiling Key - " + navigableMap.ceilingKey("Reliance"));
  System.out.println("Floor Key - " + navigableMap.floorKey("Reliance"));
  System.out.println("Higher Key - " + navigableMap.higherKey("Reliance"));
  System.out.println("Lower Key - " + navigableMap.lowerKey("Reliance"));
  
  System.out.println("Ceiling Entry - " + navigableMap.ceilingEntry("Reliance"));
  System.out.println("Floor Entry - " + navigableMap.floorEntry("Reliance"));
  System.out.println("Higher Entry - " + navigableMap.higherEntry("Reliance"));
  System.out.println("Lower Entry - " + navigableMap.lowerEntry("Reliance"));
  
  System.out.println("Poll First Entry - " + navigableMap.pollFirstEntry());
  System.out.println("Poll Last Entry - " + navigableMap.pollLastEntry());
 }
 
}



Output -

Last Key - Tata Motors
First Key - Adani
Descending Key Set - [Tata Motors, Reliance, Mahindra, Larsen, Birla, Adani]
Navigable Key Set - [Adani, Birla, Larsen, Mahindra, Reliance, Tata Motors]
Descending Map - {Tata Motors=10, Reliance=10, Mahindra=10, Larsen=2, Birla=10, Adani=10}
Head Map - {Adani=10, Birla=10, Larsen=2, Mahindra=10}
Head Map Including Key Passed - {Adani=10, Birla=10, Larsen=2, Mahindra=10, Reliance=10}
Tail Map Including Key Passed - {Reliance=10, Tata Motors=10}
Tail Map Without Key Passed - {Tata Motors=10}
Sub Map Including toKey - {Larsen=2, Mahindra=10, Reliance=10}
Sub Map without toKey and fromKey - {Mahindra=10, Reliance=10}
Ceiling Key - Reliance
Floor Key - Reliance
Higher Key - Tata Motors
Lower Key - Mahindra
Ceiling Entry - Reliance=10
Floor Entry - Reliance=10
Higher Entry - Tata Motors=10
Lower Entry - Mahindra=10
Poll First Entry - Adani=10
Poll Last Entry - Tata Motors=10

Check if two ArrayList are equal in java

Check if two ArrayList are equal in java

ArrayList is considered equals when :
1) Size of both the lists is same
2) Content of both the list is same
3) Ordering of element is same

There are two ways to check if the lists are equals
1) Using equals() method - When using this method, make sure the ordering of elements is also same. Then only this will return true
2) Using containsAll() method - This does not check for ordering of elements. It only checks if all the elements are present in other list. It returns true even if ordering of element is different.

In containsAll, the check would be listOne.containsAll(listTwo) && listTwo.containsAll(listOne)

Client File

package test;

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

public class ArrayListEquals {

 public static void main(String args[]) {
  List<Integer> integerOne = new ArrayList<Integer>();
  List<Integer> integerTwo = new ArrayList<Integer>();

  integerOne.add(10);
  integerOne.add(20);

  integerTwo.add(10);
  integerTwo.add(20);

  boolean equals = integerOne.equals(integerTwo);
  boolean containsAll = integerOne.containsAll(integerTwo)
    && integerTwo.containsAll(integerOne);

  System.out.println(equals);
  System.out.println(containsAll);
 }
}

Find Maximum Value From ArrayList In Java

Find Maximum Value From ArrayList In Java

There are three ways to get maximum value from an ArrayList:

1) Collections.max() from java.util.Collections - Pass the arraylist object to this method and it returns the max value
2) Using Iteration
3) Using Collections.sort() from java.util.Collections - Pass the arraylist object to this method. It sorts the collection from least to maximum value. Get the value at last index from the sorted list to get maximum value

Click to see Sort ArrayList Using Comparator In Java

Sample Implementation:

package test;

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

public class FindMaxIntegerArrayList {

 public static void main(String args[]) {
  List<Integer> integers = new ArrayList<Integer>();

  integers.add(1000);
  integers.add(895);
  integers.add(640);
  integers.add(1089);

  // Using java.util.Collections
  System.out.println("Maximum Element : " + Collections.max(integers));

  // Using Iteration
  Integer max = Integer.MIN_VALUE;
  for (Integer integer : integers) {
   if (integer > max) {
    max = integer;
   }
  }
  System.out.println("Maximum Element after iteration : " + max);

  // Using Sort Technique of java.util.Collections
  Collections.sort(integers);
  System.out.println("Maximum Element After Sorting - "
    + integers.get(integers.size() - 1));

 }
}

Iterate Loop List or ArrayList in Java

Iterate Loop List or ArrayList in Java in the following ways:

1) Normal for loop
2) Advance for loop
3) Using while loop
4) Using java.util.Iterator
5) Using java.util.ListIterator
6) Using remove function of List - Using remove method will make the list empty

Following is the set of Strings added in the List
1) Mesothelioma law firm
2) Sell annuity payment
3) Annuity settlements
4) Car donate
5) Motor insurance quotes
6) Auto accident attorney
7) Personal Loans

Sample Implementation

package test;

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

public class IterateLoopArrayList {

 public static void main(String args[]) {
  List<String> list = new ArrayList<String>();
  list.add("Mesothelioma law firm");
  list.add("Sell annuity payment");
  list.add("Annuity settlements");
  list.add("Car donate");
  list.add("Motor insurance quotes");
  list.add("Auto accident attorney");
  list.add("Personal Loans");

  int listSize = list.size();

  System.out
    .println("\n*****************Normal for loop*******************");
  for (int i = 0; i < listSize; i++) {
   System.out.println(list.get(i));
  }

  System.out
    .println("\n*******************Advance for loop*******************");
  for (String string : list) {
   System.out.println(string);
  }

  System.out
    .println("\n*******************Using while loop*******************");
  int j = 0;
  while (list.size() > j) {
   System.out.println(list.get(j));
   j++;
  }

  System.out
    .println("\n*******************Using Iterator*******************");
  Iterator<String> iterator = list.iterator();
  while (iterator.hasNext()) {
   System.out.println(iterator.next());
  }

  System.out
    .println("\n*******************Using List Iterator*******************");
  ListIterator<String> listIterator = list.listIterator();
  while (listIterator.hasNext()) {
   System.out.println(listIterator.next());
  }

  System.out
    .println("\n*******************Using remove function of list*******************");
  while (list.size() > 0) {
   System.out.println(list.remove(0));
  }
 }
}