Show List

Java Collections

Collection is an object that groups multiple elements in a single unit. Collections are used to store, retrieve, manipulate data. Java collections framework classes provide following benefits:

  • Because collection classes provide some key functionalities such as sorting, indexing etc., it helps to reduce the development effort.
  • These are well tested classes so code quality is improved.
  • Promotes reusability.
  • Maintenance is easy.
Here is the hierarchy of Collections. All collection classes have consistent implementation and provide some common methods like add, get, put, remove etc.

  • HashSet, HashMap, HashTable do not allow ordering
  • Set do not allow duplicate values or random access
  • List allows duplicate value and ordering
Common methods in the interface Collection:
  • size()
  • isEmpty()
  • contains()
  • iterator()
  • toArray()
  • add()
  • remove()
  • addAll()
  • removeAll()
  • removeIf()

ArrayList

ArrayList is a resizable Array. The size of the built in array can not be modified. Some additional common methods for ArrayList:
  • sort() - Declared in List
  • indexOf() - Declared in List
  • clone() - Defined in ArrayList
In the main method of the sample class below, we are creating ArrayList object and then adding elements to it. There are ArrayList methods then to add element to specific index and remove elements. Comments have been provided along with the specific statements to explain.
import java.util.ArrayList;

public class CollectionsTest {
public static void main(String args[]) {
/* Creating ArrayList of type "String"
*/
ArrayList<String> obj = new ArrayList<String>();

/* Add elements to an ArrayList*/
obj.add("Tom");
obj.add("Harry");
obj.add("Cris");
obj.add("Steve");
obj.add("Ana");

// Display the elements
System.out.println("Original ArrayList:");
for(String str:obj)
System.out.println(str);

/* Add element at the given index
*/
obj.add(0, "Robert");
obj.add(1, "Justin");

// Displaying elements
System.out.println("ArrayList after add operation:");
for(String str:obj)
System.out.println(str);

//Remove elements from ArrayList like this
obj.remove("Chamilia");
obj.remove("Harris");

// Displaying elements
System.out.println("ArrayList after remove operation:");
for(String str:obj)
System.out.println(str);

//Remove element from the specified index
obj.remove(1);

// Displaying elements
System.out.println("Final ArrayList:");
for(String str:obj)
System.out.println(str);
}
}
Output:
Original ArrayList:
Tom
Harry
Cris
Steve
Ana
ArrayList after add operation:
Robert
Justin
Tom
Harry
Cris
Steve
Ana
ArrayList after remove operation:
Robert
Justin
Tom
Harry
Cris
Steve
Ana
Final ArrayList:
Robert
Tom
Harry
Cris
Steve
Ana

Process finished with exit code 0

LinkedList

LinkedList is similar to ArrayList and stores the elements in containers that have link with the next container. It also implements Dequeue interface and provides additional method from that class as well. Common additional methods in LinkedList
  • addFirst()
  • addLast()
  • removeFirst()
  • removeLast()
  • getFirst()
  • getLast()
  • poll() - Declared in Queue. Returns and removes the head of the queue. Returns null if the queue is empty
  • peek() - Declared in Queue. Returns the head of the queue. Returns null if the queue is empty
import java.util.ArrayList;
import java.util.LinkedList;

public class CollectionsTest {
public static void main(String args[]) {
/* Creating ArrayList of type "String"
*/
LinkedList<String> obj = new LinkedList<String>();

/* Add elements to an ArrayList*/
obj.add("Tom");
obj.add("Harry");
obj.add("Chris");
obj.addFirst("Steve");
obj.addLast("Ana");

// Display the elements
System.out.println("Original ArrayList:");
for(String str:obj)
System.out.println(str);

/* Add element at the given index
*/
obj.add(0, "Robert");
obj.add(1, "Justin");

// Displaying elements
System.out.println("ArrayList after add operation:");
for(String str:obj)
System.out.println(str);

//Remove elements from ArrayList like this
obj.remove("Chamilia");
obj.removeLast();

// Displaying elements
System.out.println("ArrayList after remove operation:");
for(String str:obj)
System.out.println(str);

//Remove element from the specified index
obj.remove(1);

// Displaying elements
System.out.println("Final ArrayList:");
for(String str:obj)
System.out.println(str);
}
}
Output:
Original ArrayList:
Steve
Tom
Harry
Chris
Ana
ArrayList after add operation:
Robert
Justin
Steve
Tom
Harry
Chris
Ana
ArrayList after remove operation:
Robert
Justin
Steve
Tom
Harry
Chris
Final ArrayList:
Robert
Steve
Tom
Harry
Chris

Process finished with exit code 0

HashSet

It contains: 
  • Unique
  • Unordered items

TreeSet

It implements SortedSet class
  • Objects in a TreeSet are stored in a sorted and ascending order
In the example below, we are creating a set object using unsorted numbers. When TreeSet is created using this set the elements get sorted automatically. There are statements then to print first and last number from the TreeSet.
import java.util.*;

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

int count[] = {19, 12,87,43,21,76};
Set<Integer> set = new HashSet<Integer>();

//Add the unsorted numbers to the set
for(int i = 0; i < 5; i++) {
set.add(count[i]);
}
System.out.println(set);

//When the TreeSet is created from the set, the numbers get sorted automatically
TreeSet sortedSet = new TreeSet<Integer>(set);

System.out.println("The sorted list is:");
System.out.println(sortedSet);

//Print the first number of the TreeSet
System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());

//Print the last number of the TreeSet
System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());

}
}
Output:
[19, 21, 87, 43, 12]
The sorted list is:
[12, 19, 21, 43, 87]
The First element of the set is: 12
The last element of the set is: 87

Process finished with exit code 0

Iterator

An Iterator is an object that can be used to loop through collections.

In the example below, we are creating an iterator from an ArrayList. And then using the iterator looping through the list to print the elements.
import java.util.ArrayList;
import java.util.Iterator;

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

//Create ArrayList
ArrayList names = new ArrayList();

//Add elements to the ArrayList
names.add("David");
names.add("John");
names.add("Steve");

//Create Iterator from the ArrayList
Iterator it = names.iterator();

//Using the iterator, loop through the ArrayList elements
while(it.hasNext()) {
String obj = (String)it.next();
System.out.println(obj);
}

}
}
Output:
David
John
Steve

Process finished with exit code 0

    Leave a Comment


  • captcha text