Collections in Java
Collections in Java
Collections in Java
Java collections refer to a collection of individual objects that are represented as a single unit.
You can perform all operations such as searching, sorting, insertion, manipulation, deletion,
etc., on Java collections just like you do it on data.
public boolean hasNext() – This method returns true if the iterator has more elements.
public object next() – It returns the element and moves the cursor pointer to the next
element.
public void remove() – This method removes the last elements returned by the iterator.
Here are three components that extend the collection interface i.e List, Queue and Sets.
Let’s learn about them in detail:
Method Description
boolean add (Collection c) Appends the specified element to the end of a list.
void add (int index, Inserts the specified element at the specified position.
Object element)
void clear() Removes all the elements from this list.
int lastIndexOf (Object o) Return the index in this list of the last occurrence of the specified
element, or -1 if the list does not contain this element.
Object clone() Return a shallow copy of an ArrayList.
Object[ ] toArray() Returns an array containing all the elements in the list.
void trimToSize() Trims the capacity of this ArrayList instance to be the list’s
current size
Method Description
public boolean hasNext() It returns true if the iterator has more elements otherwise it returns
false.
public Object next() It returns the element and moves the cursor pointer to the next
element.
public void remove() It removes the last elements returned by the iterator. It is less used.
Syntax:
ArrayList object = new ArrayList ();
Some of the methods in array list are listed below:
Example:
import java.util.*;
public class list1
{
public static void main(String args[])
{
ArrayList a1 = new ArrayList();
System.out.println("size of ArrayList "+a1.size());
Linked List: Linked List is a sequence of links which contains items. Each link contains a
connection to another link.
Java Linked List class uses two types of Linked list to store the elements:
Singly Linked List
Doubly Linked List
Singly Linked List: In a singly Linked list each node in this list stores the data of the node and a pointer
or reference to the next node in the list. Refer to the below image to get a better understanding of single
Linked list.
Doubly Linked List: In a doubly Linked list, it has two references, one to the next node and another to
previous node. You can refer to the below image to get a better understanding of doubly linked list.
Method Description
addFirst() Adds an item to the beginning of the list.
addLast() Add an item to the end of the list
removeFirst() Remove an item from the beginning of the list.
removeLast() Remove an item from the end of the list
getFirst() Get the item at the beginning of the list
getLast() Get the item at the end of the list
cars.add("Ford");
cars.add("Mazda");
//System.out.println(cars);
//addFirst() Adds an item to the beginning of the list.
cars.addFirst("Mazda");
//addLast() Add an item to the end of the list
cars.addLast("Maruti");
//System.out.println(cars);
// Use removeFirst() remove the first item from the list
System.out.println("value "+cars.removeFirst());
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
2) ArrayList increments 50% of current Vector increments 100% means doubles the
array size if the number of elements array size if the total number of elements exceeds
exceeds from its capacity. than its capacity.
5) ArrayList uses the Iterator interface A Vector can use the Iterator interface
to traverse the elements. or Enumeration interface to traverse the
elements.
work on ArrayList at
Note : ArrayList is non synchronized because if ArrayList is synchronized then only one thread can
a time and rest of all threads cannot perform other operations on the ArrayList until the first thread
release the lock. This causes overhead and reduces performance. This applies for all collections.
v1.addAll(v2);
System.out.println("Vactor V1 "+v1);
System.out.println("Index of 1 "+v1.indexOf(1));
System.out.println("Size of Vactor V1 "+v1.size());
System.out.println("Capacity is: "+v1.capacity());
System.out.println("is Vactor V1 empty "+v1.isEmpty());
System.out.println("15 is contain Vactor V1
"+v1.contains(15));
System.out.println("11 is contain Vactor V1
"+v1.contains(11));
}
}
stack
The stack is a linear data structure that is used to store the collection of objects. It is
based on Last-In-First-Out (LIFO).
Java collection framework provides many interfaces and classes to store the collection
of objects.
In this section, we will discuss the Java Stack class, its methods, and implement the
stack data structure in a Java program.
The stack data structure has the two most important operations that are push and pop.
The push operation inserts an element into the stack and pop operation removes an
element from the top of the stack.
Creation of stack
Stack stk = new Stack();
Or
Stack<type> stk = new Stack<type>();
import java.util.*;
class stack1{
boolean r = s1.empty();
System.out.println("Is the stack empty? " + r);
// items to push
s1.push("Dell");
s1.push("HP");
s1.push("HCL");
s1.push("lenovo");
// Search an element
int loc = s1.search("HCL");
System.out.println("Location of Dell: " + loc);
// Find the size of the Stack
int s =s1.size();
System.out.println("The stack size is: "+s);
}
O/P :
Is the stack empty? true
Elements in Stack: [Dell, HP, HCL, lenovo]
Is the stack empty? false
pop -> Peeked element: lenovo
Location of Dell: 2
The stack size is: 4
Queue
A Queue is designed in such a way so that the elements added to it are placed at the end of
Queue and removed from the beginning of Queue.
The concept here is similar to the queue we see in our daily life, for example, when a new
iPhone launches we stand in a queue outside the apple store, whoever is added to the queue has
to stand at the end of it and persons are served on the basis of FIFO (First In First Out), The
one who gets the iPhone is removed from the beginning of the queue.
import java.util.*;
class queue
{
q.add("Maggie");
q.add("Yappie");
q.add("yoymee");
q.add("knorr");
System.out.println("Elements in Queue:"+q);
System.out.println("Removed element: "+q.remove());
System.out.println("Head: "+q.element());
System.out.println("poll(): "+q.poll());
}
}
Example : 2
import java.util.*;
class queue2
{
public static void main(String args[])
{
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
this.quantity = quantity;
}
public int compareTo(Book b)
{
System.out.println("object "+b);
System.out.println("ID "+id);
if(id>b.id)
{
return 1;
}
else if(id<b.id)
{
return -1;
}
else
return 0;
}
}
}
TreeSet
TreeSet class used to store unique elements in ascending order. It is similar
to HashSet except that it sorts the elements in the ascending order while HashSet doesn’t
maintain any order.
Java TreeSet class implements the Set interface and use tree based data structure storage. It
extends AbstractSet class and implements the NavigableSet interface. Some important Points
Method Description
boolean add(E e) It adds the specified element to this set if it is not already present.
boolean addAll(Collection<? extends E> c) It adds all of the elements in the specified collection to this set.
E pollFirst() It is used to retrieve and remove the lowest(first) element.
E pollLast() It is used to retrieve and remove the highest(last) element.
boolean contains(Object o) It returns true if this set contains the specified element.
boolean isEmpty() It returns true if this set contains no elements.
boolean remove(Object o) It is used to remove the specified element from this set if it is present.
void clear() It is used to remove all of the elements from this set.
Object clone() It returns a shallow copy of this TreeSet instance.
E first() It returns the first (lowest) element currently in this sorted set.
E last() It returns the last (highest) element currently in this sorted set.
int size() It returns the number of elements in this set.
Example :1
import java.util.*;
public class tree
{
public static void main(String[] args)
{
//Creating a TreeSet
set.add(20);
set.add(10);
set.add(40);
set.add(80);
set.add(30);
//Traversing elements
/*Iterator<String> itr=set.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}*/
}
}
Example :3
import java.util.*;
class tree_3
{
public static void main(String args[])
{
TreeSet <Integer> T = new TreeSet<Integer>();
T.add(23);
T.add(66);
T.add(85);
T.add(10);
T.add(25);
System.out.println(T);
T.remove(23);
System.out.println("After Removing: "+T);
boolean t = T.contains(85);
System.out.println("Is contain Ravi: "+t);
int h =T.pollFirst();
Java HashMap
HashMap <K, V> is a part of Java’s collection since Java 1.2. This class is found in
java.util package.
It provides the basic implementation of the Map interface of Java. It stores the data in
(Key, Value) pairs, and you can access them by an index of another type (e.g. an
Integer). One object is used as a key (index) to another object (value). If you try to insert
the duplicate key, it will replace the element of the corresponding key.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It
allows us to store the null elements as well, but there should be only one null key. Since
Java 5, it is denoted as HashMap<K,V>, where K stands for key and V for value. It
inherits the AbstractMap class and implements the Map interface
Points to remember
Java HashMap contains values based on the key.
Java HashMap contains only unique keys.
Java HashMap may have one null key and multiple null values.
Java HashMap is non synchronized.
Java HashMap maintains no order.
import java.util.HashMap;
public class hash1
{
public static void main(String[] args)
{
// Create an empty hash map by declaring object of string and
integer type
HashMap<String, Integer> map = new HashMap<>();
// Mapping
Integer a = map.get("vishal");
}
}
Example-2
import java.util.HashMap;
people.put(34,"Niha_kakar");
people.put(33,"Goutami");
people.put(36,"Dinesh");
// Printing elements in object of Map
System.out.println(people);
//To remove an item, use the remove() method and refer to the key:
System.out.println("Deleted item "+people.remove(36));