Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

Java Collections

 Collections are an interface in the java.util package, and as its


name suggests, it is used to define a collection of objects.

 There are many different classes which implement the collections


interface.

Collections Interfaces
The Java Collection interface (java.util.Collection) is one of the
root interfaces of the Java Collection API.. Though you do not
instantiate a Collection directly, but rather a subtype of
Collection, you may often treat these subtypes uniformly as a
Collection.
Create a Collection
As just mentioned above, you do not create a Collection instance
directly, but an instance of one of the subtypes of Collection. Here is an
example of creating a List which is a subtype of Collection:

Collection collection = new ArrayList();

Collection Subtypes
The following interfaces (collection types) extends
the Java Collection interface:

 List
 Set
 SortedSet
 NavigableSet
 Queue
 Deque

Java does not come with a usable implementation of the Collection interface,
so you will have to use one of the listed subtypes. The Collection interface just
defines a set of methods (behaviour) that each of these Collection subtypes
share. This makes it possible ignore what specific type of Collection you are
using, and just treat it as a Collection.

Collection interface methods

 boolean add(Object obj)

Adds obj to the invoking collection. Returns true if obj was


added to the collection. Returns false if obj is already a member of
the collection, or if the collection does not allow duplicates.

 void clear( )
Removes all elements from the invoking collection.

 boolean contains(Object obj)

Returns true if obj is an element of the invoking collection.


Otherwise, returns false.

 boolean equals(Object obj)

Returns true if the invoking collection and obj are equal.


Otherwise, returns false.

 int hashCode( )

Returns the hash code for the invoking collection.

 boolean isEmpty( )

Returns true if the invoking collection is empty. Otherwise,


returns false.

 boolean remove(Object obj)

Removes one instance of obj from the invoking collection.


Returns true if the element was removed. Otherwise, returns
false.

 int size( )

Returns the number of elements held in the invoking


collection.
Generic Collections

It is possible to specify generic types for most (if not all) of the
components in the Java Collections API.

When you set a generic type for a Java Collection, you do so when you
declare the variable referencing it. Here is an example of setting the generic
type of a Collection and HashSet to a Java String - meaning it can only
contain String instances:

Collection<String> stringCollection = new HashSet<String>();

This stringCollection can now only contain String instances. If


you try to add anything else, or cast the elements in the collection to any other
type than String, the compiler will complain.

You can specify a generic type for a List's, Set's etc.

Generic Iterator
When you have specified a generic type for a Java collection, that generic
type also works for the Iterator returned by the iterator() method. Here
is an example of how obtaining an Iterator with a generic type set on it looks:

Iterator<String> iterator = stringCollection.iterator();

You can iterate the elements of this Iterator like this:

while(iterator.hasNext()) {
String element = iterator.next();
//do something with element.
}
Notice how it is not necessary to cast the String returned from
the iterator.next() method call. Because the Iterator has its generic
type set to String, the Java compiler already knows that next() will return a
String.

Generic Iteration Using for Loop


You can also iterate the above collection using the new for-loop, like this:

Collection<String> stringCollection = new HashSet<String>();

for(String stringElement : stringCollection) {


//do something with each stringElement
}

List

The Java List interface, java.util.List, represents an ordered


sequence of objects. The elements contained in a Java List can be
inserted, accessed, iterated and removed according to the order in which they
appear internally in the Java List. The ordering of the elements is why this
data structure is called a List.

Each element in a Java List has an index. The first element in


the List has index 0, the second element has index 1 etc. The index means
"how many elements away from the beginning of the list". The first element is
thus 0 elements away from the beginning of the list - because it is at the
beginning of the list.

You can add any Java object to a List. If the List is not typed, using Java
Generics, then you can even mix objects of different types (classes) in the
same List. Mixing objects of different types in the same List is not often
done in practice, however.

The Java List interface is a standard Java interface, and it is a subtype of


the Java Collection interface, meaning List inherits from Collection.
List Interface

The List interface extends Collection and declares the behavior of


a collection that stores a sequence of elements.

 Elements can be inserted or accessed by their position in the list,


using a zero-based index.

 A list may contain duplicate elements.

 In addition to the methods defined by Collection, List defines


some of its own, which are summarized in the following

 List interface is implemented by the classes ArrayList, LinkedList,


Vector, and Stack.

List Interface Methods


 void add(int index, Object obj)
Inserts obj into the invoking list at the index passed in index.
Any preexisting elements at or beyond the point of insertion are
shifted up. Thus, no elements are overwritten.
 Object get(int index)
Returns the object stored at the specified index within the
invoking collection.
 int indexOf(Object obj)
Returns the index of the first instance of obj in the invoking
list. If obj is not an element of the list, -1 is returned.
 int lastIndexOf(Object obj)
Returns the index of the last instance of obj in the invoking
list. If obj is not an element of the list, -1 is returned
 Object remove(int index)
Removes the element at position index from the invoking
list and returns the deleted element. The resulting list is
compacted. That is, the indexes of subsequent elements are
decremented by one
 Object set(int index, Object obj)
Assigns obj to the location specified by index within the
invoking list.

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

listA.add("element 1");
listA.add("element 2");
listA.add("element 3");

Set Interface
 A Set is a Collection that cannot contain duplicate elements.
 The Set interface contains only methods inherited from Collection
and adds the restriction that duplicate elements are prohibited.
The Java Set interface, java.util.Set, represents a collection of objects
where each object in the Java Set is unique. In other words, the same object
cannot occur more than once in a Java Set. The Java Set interface is a
standard Java interface, and it is a subtype of the Java Collection interface,
meaning Set inherits from Collection.

You can add any Java object to a Java Set. If the Set is not typed,
using Java Generics, then you can even mix objects of different types
(classes) in the same Set. Mixing objects of different types in the
same Set is not often done in reality, however.
Java Set vs. List
The Java Set and Java List interfaces are quite similar to each other. Bot
interfaces represents a collection of elements. However, there are some
significant differences. These differences are reflected in the methods
the Set and List interfaces contain.

The first difference between the Java Set and List interface is, that the
same element cannot occur more than once in a Java Set. This is different
from a Java List where each element can occur more than once.

The second difference between a Java Set and Java List interfaces is,
that the elements in a Set has no guaranteed internal order. The elements in
a List has an internal order, and the elements can be iterated in that order.

import java.util.HashSet;

public class SetExample {

public static void main(String[] args) {

Set setA = new HashSet();

setA.add(element);

System.out.println( setA.contains(element) );
}
}

SortedSet Interface

 The SortedSet interface extends Set and declares the behavior of


a set sorted in ascending order.
 In addition to those methods defined by Set, the SortedSet
interface declares the methods summarized in below
The Java SortedSet interface, java.util.SortedSet, is a subtype of
the java.util.Set interface. The Java SortedSet interface behaves
like a normal Set with the exception that the elements it contains are sorted
internally. This means that when you iterate the elements of SortedSet the
elements are iterated in the sorted order.

SortedSet Methods
 Object first( )
Returns the first element in the invoking sorted set.
 Object last( )
Returns the last element in the invoking sorted set.
 SortedSet subSet(Object start, Object end)
Returns a SortedSet that includes those elements
between start and end-1. Elements in the returned collection are
also referenced by the invoking object.
 SortedSet headSet(Object end)
Returns a SortedSet containing those elements less than
end that are contained in the invoking sorted set.
 SortedSet tailSet(Object start)
Returns a SortedSet that contains those elements greater
than or equal to start that are contained in the sorted set.

SortedSet sortedSet = new TreeSet();

Enumeration & Iterator


Iterator and Enumeration both are the cursors to traverse and
access an element from the collection. They both belong to the
collection framework. Enumeration was added in JDK1.0 and
Iterator in the JDK.1.2 version in the collection framework.

Enumeration can’t make structural changes in the collection because it


has read-only access to the element in the collection. It has the
following methods :
hasMoreElements()
nextElement()
On the other hand, an iterator can read and remove the element in the
collection. It has the following methods −
hasNext()
next()
remove()

LinkedList
 The LinkedList class extends AbstractSequentialList and
implements the List interface.
 Apart from the methods inherited from its parent classes,
LinkedList defines following methods
LinkedList Methods
 void addFirst(Object o)
Inserts the given element at the beginning of this list.
 void addLast(Object o)
Appends the given element to the end of this list.
 Object getFirst()
Returns the first element in this list.
 Object getLast()
Returns the last element in this list
 Object removeFirst()
Removes and returns the first element from this list.
 Object removeLast()
Removes and returns the last element from this list.

LinkedList Example
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
LinkedList ll = new LinkedList();
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll:"+ll);
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion:"+ll);
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last:"+ll);
}}
ArrayList
 The ArrayList class extends AbstractList and implements
the List interface. ArrayList supports dynamic arrays that
can grow as needed.
 Standard Java arrays are of a fixed length. After arrays are
created, they cannot grow or shrink, which means that you
must know in advance how many elements an array will
hold.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
ArrayList al = new ArrayList();
size of al:"+al.size());
System.out.println("Initial size
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions:"+al.size());
System.out.println("Contents of al: " + al);
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions:"+al.size());
System.out.println("Contents of al: " + al);
}}

Vector
 Vector implements a dynamic array. It is similar to
ArrayList, but with two differences:
 Vector is synchronized.
 Vector contains many legacy methods that are not part of
the collections framework.
Vector Methods
 void addElement(Object obj)
Adds the specified component to the end of this vector,
increasing its size by one.
 Object firstElement()
Returns the first component (the item at index 0) of this
vector.
 Object lastElement()
Returns the last component of the vector.
 void setSize(int newSize)
Sets the size of this vector.
Ex:
import java.util.*;
class VectorDemo {
public static void main(String args[]) {
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity:"+v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four
additions:"+v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity:"+v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity:"+v.capacity());
System.out.println("First element:"+v.firstElement());
System.out.println("Last element:"+v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
Enumeration vEnum = v.elements();
System.out.println("\nElements
System.out.println(" nElements in vector:");
while(vEnum.hasMoreElements())
while(vEnum.h
System.out.print(vEnum.nextElement() + " ");
System.out.println(); }}

Stack

 Stack is a subclass of Vector that implements a standard


last-in, first-out
out stack.
 Stack includes all the methods defined by Vector, and adds
several of its own.
Stack Methods
 Object peek( )
Returns the element on the top of the stack, but does not
remove it.
 Object pop( )
Returns the element on the top of the stack, removing it in
the process.
 Object push(Object element)
Pushes element onto the stack. element is also returned.
 int search(Object element)
Searches for element in the stack. If found, its offset from
the top of the stack is returned. Otherwise, -1 is returned.

Stack Example
import java.util.*;
class stackDemo {
public static void main(String args[]) {
Stack s=new Stack();
s.push(new Integer(10));
s.push(new Integer(20));
s.push(new Integer(30));
System.out.println("Elements:"+s);
System.out.println(s.peek());
System.out.println("Elements:"+s);
println("Elements:"+s);
s.pop();
System.out.println("Elements:"+s);
}}

HashSet
HashSet extends AbstractSet and implements the Set
interface.
HashSet Example
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
HashSet hs = new HashSet();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
} }
HashSet Example
import java.util.*;
ava.util.*;
class HashSetDemo {
public static void main(String args[]) {
HashSet hs = new HashSet();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("A");//duplicate value
System.out.println(hs);
}}

LinkedHashSet
import java.util.*;
class LinkedHashSetDemo
HashSetDemo {
public static void main(String args[]) {
LinkedHashSet hs = new LinkedHashSet();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs); } }

TreeSet

 TreeSet provides an implementation of the Set


interface that uses a tree for storage.
 Objects are stored in sorted, ascending order.
TreeSet Example
import java.util.*;
class SortedSetDemo
etDemo {
public static void main(String args[]) {
TreeSet hs = new TreeSet();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}}

TreeSet Example
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
TreeSet hs = new TreeSet(Collections.reverseOrder());
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}}

Map Interface
 The Map interface maps unique keys to values. A key is an
object that you use to retrieve a value at a later date.
 Given a key and a value, you can store the value in a Map
object. After the value is stored, you can retrieve it by
using its key.
Map Interface Methods
 void clear( )
Removes all key/value pairs from the invoking map.
 boolean containsKey(Object k)
Returns true if the invoking map contains k as a key.
Otherwise, returns false.
 boolean containsValue(Object v)
Returns true if the map contains v as a value. Otherwise,
returns false.
 Object get(Object k)
Returns the value associated with the key k.
 boolean isEmpty( )
Returns true if the invoking map is empty. Otherwise,
returns false.
 Object put(Object k, Object v)
Puts an entry in the invoking map, overwriting any
previous value associated with the key. The key and value are
k and v, respectively. Returns null if the key did not already
exist. Otherwise, the previous value linked to the key is
returned.
 Object remove(Object k)
Removes the entry whose key equals k.
 int size( )
Returns the number of key/value pairs in the map.
SortedMap
 The SortedMap interface extends Map.
 It ensures that the entries are maintained in ascending key
order
SortedMap Methods
 Object firstKey( )
Returns the first key in the invoking map.
 SortedMap headMap(Object end)
Returns a sorted map for those map entries with keys that
are less than end.
 Object lastKey( )
Returns the last key in the invoking map.
 SortedMap subMap(Object start, Object end)
Returns a map containing those entries with keys that are
greater than or equal to start and less than end
 SortedMap tailMap(Object start)
Returns a map containing those entries with keys that are
greater than or equal to start.
HashMap Example
import java.util.*;
class hashmapdemo{
public static void main(String args[]){
HashMap h=new HashMap();
h.put(1,new String("one"));
h.put(5,new String("five"));
h.put(2,new String("two"));
System.out.println("Elements:"+h);
System.out.println(h.get(5));
h.remove(5);
System.out.println("Elements:"+h);
} }
HashMap Example
import java.util.*;
class hashmapdemo{
public static void main(String args[]){
HashMap h=new HashMap();
h.put(1,new String("one"));
h.put(new String("hello"),new String("five"));
h.put(2,new Stri
String("two"));
h.put(new Character('a'),new String("kkkk"));
h.put(new Character('A'),new String("lll"));
h.put(new Character('b'), new String("jjjj"));
System.out.println("Elements:"+h);
} }

TreeMap Example
import java.util.*;
class hashmapdemo{
public static void main(String args[]){
TreeMap t=new TreeMap();
t.put(1,new String("one"));
t.put(5,new String("five"));
t.put(2,new String("two"));
System.out.println("Elements:"+t);
System.out.println("Ele
}}

TreeMap Example
import java.util.*;
class hashmapdemo{
public static void main(String args[]){
TreeMap t=new TreeMap();
t.put(new Character('B'),new Integer(10));
t.put(new Character('C'),new Intege
Integer(20));
r(20));
t.put(new Character('A'),new Integer(30));
System.out.println("Elements:"+t);
}}
Queue Interface

The interface Queue is available in the java.util package and does extend
the Collection interface. It is used to keep the elements that are processed
in the First In First Out (FIFO) manner. It is an ordered list of objects, where
insertion of elements occurs at the end of the list, and removal of elements
occur at the beginning of the list.

requires, for the declaration, a concrete class,


Being an interface, the queue requires,
and the most common classes are the LinkedList and PriorityQueue in Java.

Method Description

boolean It is used to insert the specified element into this queue and return true upon
add(object) success.

boolean It is used to insert the specified element into this queue.


offer(object)

Object remove() It is used to retrieves and removes the head of this queue.

Object poll() It is used to retrieves and removes the head of this queue, or returns null if this
queue is empty.

Object element() It is used to retrieves, but does not remove, the head of this queue.

Object peek() It is used to retrieves, but does not remove, the head of this queue, or returns
null if this queue is empty.
PriorityQueue :

public class demo {


public static void main(String [] args){
PriorityQueue q=new PriorityQueue();
System.out.println(q);
q.offer(new Integer(10));
q.offer(new Integer(20));
q.offer(new Integer(30));
System.out.println(q);
System.out.println(q.peek());
System.out.println(q);
System.out.println(q.poll());
System.out.println(q);
System.out.println(q.remove());
System.out.println(q);
}
}
Output:

[]
[10, 20, 30]
10
[10, 20, 30]
10
[20, 30]
20
[30]
Deque Interface
The interface called Deque is present in java.util package. It is the subtype of the
interface queue. The Deque supports the addition as well as the removal of elements
from both ends of the data structure. Therefore, a deque can be used as a stack or a
queue. We know that the stack supports the Last In First Out (LIFO) operation, and the
operation First In First Out is supported by a queue. As a deque supports both, either of
the mentioned operations can be performed on it. Deque is an acronym for "double
ended queue".

Methods of Java Deque Interface


Method Description

boolean It is used to insert the specified element into this deque and return true upon success.
add(object)

boolean It is used to insert the specified element into this deque.


offer(object)

Object remove() It is used to retrieve and removes the head of this deque.

Object poll() It is used to retrieve and removes the head of this deque, or returns null if this deque is
empty.

Object element() It is used to retrieve, but does not remove, the head of this deque.

Object peek() It is used to retrieve, but does not remove, the head of this deque, or returns null if this
deque is empty.

Object The method returns the head element of the deque. The method does not remove any
peekFirst() element from the deque. Null is returned by this method, when the deque is empty.

Object The method returns the last element of the deque. The method does not remove any
peekLast() element from the deque. Null is returned by this method, when the deque is empty.

Boolean Inserts the element e at the front of the queue. If the insertion is successful, true is returned;
offerFirst(e) otherwise, false.

Object Inserts the element e at the tail of the queue. If the insertion is successful, true is returned;
offerLast(e) otherwise, false.

ArrayDeque class
We know that it is not possible to create an object of an interface in Java. Therefore, for
instantiation, we need a class that implements the Deque interface, and that class is
ArrayDeque. It grows and shrinks as per usage. It also inherits the AbstractCollection
class.

The important points about ArrayDeque class are:

o Unlike Queue, we can add or remove elements from both sides.


o Null elements are not allowed in the ArrayDeque.
o ArrayDeque is not thread safe, in the absence of external synchronization.
o ArrayDeque has no capacity restrictions.
o ArrayDeque is faster than LinkedList and Stack.

1. import java.util.*;
2. public class ArrayDequeExample {
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Ravi");
7. deque.add("Vijay");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }

1. import java.util.*;
2. public class DequeExample {
3. public static void main(String[] args) {
4. Deque<String> deque=new ArrayDeque<String>();
5. deque.offer("arvind");
6. deque.offer("vimal");
7. deque.add("mukul");
8. deque.offerFirst("jai");
9. System.out.println("After offerFirst Traversal...");
10. for(String s:deque){
11. System.out.println(s);
12. }
13. //deque.poll();
14. //deque.pollFirst();//it is same as poll()
15. deque.pollLast();
16. System.out.println("After pollLast() Traversal...");
17. for(String s:deque){
18. System.out.println(s);
19. }
20. }
21. }
Comparator Interface
A comparator interface is used to order the objects of user-defined classes. A comparator
object is capable of comparing two objects of the same class.

Syntax:
public int compare(Object obj1, Object obj2)

// Java Program to Demonstrate Working of


// Comparator Interface

// Importing required classes


import java.io.*;
import java.lang.*;
import java.util.*;

// Class 1
// A class to represent a Student
class Student {

// Attributes of a student
int rollno;
String name, address;

// Constructor
public Student(int rollno, String name, String address)
{

// This keyword refers to current instance itself


this.rollno = rollno;
this.name = name;
this.address = address;
}

// Method of Student class


// To print student details in main()
public String toString()
{

// Returning attributes of Student


return this.rollno + " " + this.name + " "
+ this.address;
}
}

// Class 2
// Helper class implementing Comparator interface
class Sortbyroll implements Comparator<Student> {

// Method
// Sorting in ascending order of roll number
public int compare(Student a, Student b)
{

return a.rollno - b.rollno;


}
}

// Class 3
// Helper class implementing Comparator interface
class Sortbyname implements Comparator<Student> {

// Method
// Sorting in ascending order of name
public int compare(Student a, Student b)
{

return a.name.compareTo(b.name);
}
}

// Class 4
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an empty ArrayList of Student type


ArrayList<Student> ar = new ArrayList<Student>();

// Adding entries in above List


// using add() method
ar.add(new Student(111, "Mayank", "london"));
ar.add(new Student(131, "Anshul", "nyc"));
ar.add(new Student(121, "Solanki", "jaipur"));
ar.add(new Student(101, "Aggarwal", "Hongkong"));
// Display message on console for better readability
System.out.println("Unsorted");

// Iterating over entries to print them


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

// Sorting student entries by roll number


Collections.sort(ar, new Sortbyroll());

// Display message on console for better readability


System.out.println("\nSorted by rollno");

// Again iterating over entries to print them


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

// Sorting student entries by name


Collections.sort(ar, new Sortbyname());

// Display message on console for better readability


System.out.println("\nSorted by name");

// // Again iterating over entries to print them


for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
}
}
Collection Algorithms
The collections framework defines several algorithms that can be applied to collections
and maps.
These algorithms are defined as static methods within the Collections class. Several of
the methods can throw a ClassCastException, which occurs when an attempt is
made to compare incompatible types, or an UnsupportedOperationException, which
occurs when an attempt is made to modify an unmodifiable collection.
The methods defined in collection framework's algorithm are summarized in the
following table –

Sr.No. Method & Description

1 static int binarySearch(List list, Object value, Comparator c)


Searches for value in the list ordered according to c. Returns the position
of value in list, or -1 if value is not found.

2 static int binarySearch(List list, Object value)


Searches for value in the list. The list must be sorted. Returns the position
of value in list, or -1 if value is not found.

3 static void copy(List list1, List list2)


Copies the elements of list2 to list1.

4 static Enumeration enumeration(Collection c)


Returns an enumeration over c.

5 static void fill(List list, Object obj)


Assigns obj to each element of the list.

6 static int indexOfSubList(List list, List subList)


Searches list for the first occurrence of subList. Returns the index of the
first match, or -1 if no match is found.
7 static int lastIndexOfSubList(List list, List subList)
Searches list for the last occurrence of subList. Returns the index of the
last match, or -1 if no match is found.

8 static ArrayList list(Enumeration enum)


Returns an ArrayList that contains the elements of enum.

9 static Object max(Collection c, Comparator comp)


Returns the maximum element in c as determined by comp.

10 static Object max(Collection c)


Returns the maximum element in c as determined by natural ordering. The
collection need not be sorted.

11 static Object min(Collection c, Comparator comp)


Returns the minimum element in c as determined by comp. The collection
need not be sorted.

12 static Object min(Collection c)


Returns the minimum element in c as determined by natural ordering.

13 static List nCopies(int num, Object obj)


Returns num copies of obj contained in an immutable list. num must be
greater than or equal to zero.

14 static boolean replaceAll(List list, Object old, Object new)


Replaces all occurrences of old with new in the list. Returns true if at least
one replacement occurred. Returns false, otherwise.

15 static void reverse(List list)


Reverses the sequence in list.
16 static Comparator reverseOrder( )
Returns a reverse comparator.

17 static void rotate(List list, int n)


Rotates list by n places to the right. To rotate left, use a negative value
for n.

18 static void shuffle(List list, Random r)


Shuffles (i.e., randomizes) the elements in the list by using r as a source
of random numbers.

19 static void shuffle(List list)


Shuffles (i.e., randomizes) the elements in list.

20 static Set singleton(Object obj)


Returns obj as an immutable set. This is an easy way to convert a single
object into a set.

21 static List singletonList(Object obj)


Returns obj as an immutable list. This is an easy way to convert a single
object into a list.

22 static Map singletonMap(Object k, Object v)


Returns the key/value pair k/v as an immutable map. This is an easy way
to convert a single key/value pair into a map.

23 static void sort(List list, Comparator comp)


Sorts the elements of list as determined by comp.

24 static void sort(List list)


Sorts the elements of the list as determined by their natural ordering.
25 static void swap(List list, int idx1, int idx2)
Exchanges the elements in the list at the indices specified by idx1 and
idx2.

26 static Collection synchronizedCollection(Collection c)


Returns a thread-safe collection backed by c.

27 static List synchronizedList(List list)


Returns a thread-safe list backed by list.

28 static Map synchronizedMap(Map m)


Returns a thread-safe map backed by m.

29 static Set synchronizedSet(Set s)


Returns a thread-safe set backed by s.

30 static SortedMap synchronizedSortedMap(SortedMap sm)


Returns a thread-safe sorted set backed by sm.

31 static SortedSet synchronizedSortedSet(SortedSet ss)


Returns a thread-safe set backed by ss.

32 static Collection unmodifiableCollection(Collection c)


Returns an unmodifiable collection backed by c.

33 static List unmodifiableList(List list)


Returns an unmodifiable list backed by the list.

34 static Map unmodifiableMap(Map m)


Returns an unmodifiable map backed by m.
35 static Set unmodifiableSet(Set s)
Returns an unmodifiable set backed by s.

36 static SortedMap unmodifiableSortedMap(SortedMap sm)


Returns an unmodifiable sorted map backed by sm.

37 static SortedSet unmodifiableSortedSet(SortedSet ss)


Returns an unmodifiable sorted set backed by ss.

Example:
import java.util.*;
public class AlgorithmsDemo {

public static void main(String args[]) {

// Create and initialize linked list


LinkedList ll = new LinkedList();
ll.add(new Integer(-8));
ll.add(new Integer(20));
ll.add(new Integer(-20));
ll.add(new Integer(8));

// Create a reverse order comparator


Comparator r = Collections.reverseOrder();

// Sort list by using the comparator


Collections.sort(ll, r);

// Get iterator
Iterator li = ll.iterator();
System.out.print("List sorted in reverse: ");

while(li.hasNext()) {
System.out.print(li.next() + " ");
}
System.out.println();
Collections.shuffle(ll);

// display randomized list


li = ll.iterator();
System.out.print("List shuffled: ");

while(li.hasNext()) {
System.out.print(li.next() + " ");
}
System.out.println();
System.out.println("Minimum: " + Collections.min(ll));
System.out.println("Maximum: " + Collections.max(ll));
}
}

Output
List sorted in reverse: 20 8 -8 -20
List shuffled: 20 -20 8 -8
Minimum: -20
Maximum: 20

Arrays class
The Arrays class in java.util package is a part of the Java Collection Framework. This
class provides static methods to dynamically create and access Java arrays. It consists
of only static methods and the methods of Object class. The methods of this class can be
used by the class name itself.

Methods Action Performed

Returns a fixed-size list backed by the specified


asList() Arrays

Searches for the specified element in the array


binarySearch(array,key) with the help of the Binary Search Algorithm

Searches a range of the specified array for the


binarySearch(array, fromIndex, specified object using the Binary Search
toIndex, key, Comparator) Algorithm

Compares two arrays passed as parameters


compare(array 1, array 2) lexicographically.

Copies the specified array, truncating or


copyOf(originalArray, padding with the default value (if necessary) so
newLength) the copy has the specified length.

copyOfRange(originalArray, Copies the specified range of the specified


fromIndex, endIndex) array into a new Arrays.
Methods Action Performed

deepEquals(Object[] a1, Object[] Returns true if the two specified arrays are
a2) deeply equal to one another.

Returns a hash code based on the “deep


deepHashCode(Object[] a) contents” of the specified Arrays.

Returns a string representation of the “deep


deepToString(Object[] a) contents” of the specified Arrays.

equals(array1, array2) Checks if both the arrays are equal or not.

Assigns this fill value to each index of this


fill(originalArray, fillValue) arrays.

Returns an integer hashCode of this array


hashCode(originalArray) instance.

Finds and returns the index of the first


unmatched element between the two specified
mismatch(array1, array2) arrays.

parallelPrefix(originalArray,
fromIndex, endIndex, Performs parallelPrefix for the given range of
functionalOperator) the array with the specified functional operator.

parallelPrefix(originalArray, Performs parallelPrefix for complete array with


operator) the specified functional operator.

parallelSetAll(originalArray, Sets all the elements of this array in parallel,


functionalGenerator) using the provided generator function.

parallelSort(originalArray) Sorts the specified array using parallel sort.

setAll(originalArray, Sets all the elements of the specified array


functionalGenerator) using the generator function provided.

sort(originalArray) Sorts the complete array in ascending order.


Methods Action Performed

sort(originalArray, fromIndex, Sorts the specified range of array in ascending


endIndex) order.

sort(T[] a, int fromIndex, int Sorts the specified range of the specified array
toIndex, Comparator< super T> of objects according to the order induced by the
c) specified comparator.

sort(T[] a, Comparator< super Sorts the specified array of objects according to


T> c) the order induced by the specified comparator.

Returns a Spliterator covering all of the


spliterator(originalArray) specified Arrays.

Returns a Spliterator of the type of the array


spliterator(originalArray, covering the specified range of the specified
fromIndex, endIndex) arrays.

Returns a sequential stream with the specified


stream(originalArray) array as its source.

It returns a string representation of the contents


of this array. The string representation consists
of a list of the array’s elements, enclosed in
square brackets (“[]”). Adjacent elements are
separated by the characters a comma followed
by a space. Elements are converted to strings
toString(originalArray) as by String.valueOf() function.

import java.util.Arrays;
// Main class
class Demo {
public static void main(String[] args)
{
// Get the Array
int intArr[] = { 10, 20, 15, 22, 35 };
System.out.println("Integer Array as List: "
+ Arrays.asList(intArr));
}
}

Legacy Classes
Early version of java did not include the Collections framework. It only defined
several classes and interfaces that provide methods for storing objects. When
Collections framework was added in J2SE 1.2, the original classes were
reengineered to support the collection interface. These classes are also known
as Legacy classes. All legacy classes and interface were redesign by JDK 5 to
support Generics. In general, the legacy classes are supported because there is
still some code that uses them.

The following are the legacy classes defined by java.util package

1. Dictionary

2. HashTable

3. Properties

4. Stack

5. Vector
There is only one legacy interface called Enumeration

NOTE: All the legacy classes are synchronized

Enumeration interface

1. Enumeration interface defines method to enumerate(obtain one at a


time) through collection of objects.

2. This interface is superseded(replaced) by Iterator interface.

3. However, some legacy classes such as Vector and Properties defines


several method in which Enumeration interface is used.

4. It specifies the following two methods

boolean hasMoreElements() //It returns true while


there are still more elements to extract,and returns
false when all the elements have been enumerated.

Object nextElement() //It returns the next object in


the enumeration i.e. each call to nextElement()
method

obtains the next object in the enumeration. It throws


NoSuchElementException when the enumeration is
complete.

Vector class
1. Vector is similar to ArrayList which represents a dynamic array.
2. There are two differences between Vector and ArrayList. First, Vector is
synchronized while ArrayList is not, and Second, it contains many legacy
methods that are not part of the Collections Framework.

3. With the release of JDK 5, Vector also implements Iterable. This means
that Vector is fully compatible with collections, and a Vector can have its
contents iterated by the for-each loop.

4. Vector class has following four constructor

Vector() //This creates a default vector, which has


an initial size of 10.

Vector(int size) //This creates a vector whose


initial capacity is specified by size.

Vector(int size, int incr) //This creates a vector


whose initial capacity is specified by size and whose
increment is specified by incr. The increment
specifies the number of elements to allocate each
time when a vector is resized for addition of
objects.

Vector(Collection c) //This creates a vector that


contains the elements of collection c.

Vector defines several legacy methods. Lets see some important legacy
methods defined by Vector class.

Method Description
void addElement(E element) adds element to the Vector

E elementAt(int index) returns the element at specified index

Enumeration elements() returns an enumeration of element in vector

E firstElement() returns first element in the Vector

E lastElement() returns last element in the Vector

void removeAllElements() removes all elements of the Vector

Example of Vector

import java.util.*;

public class Test

public static void main(String[] args)

Vector<Integer> ve = new Vector<Integer>();

ve.add(10);
ve.add(20);

ve.add(30);

ve.add(40);

ve.add(50);

ve.add(60);

Enumeration<Integer> en = ve.elements();

while(en.hasMoreElements())

System.out.println(en.nextElement());

10

20

30

40

50

60

Hashtable class
1. Like HashMap, Hashtable also stores key/value pair. However
neither keys nor values can be null.

2. There is one more difference between HashMap and Hashtable that is


Hashtable is synchronized while HashMap is not.

3. Hashtable has following four constructor

Hashtable() //This is the default constructor. The


default size is 11.

Hashtable(int size) //This creates a hash table that


has an initial size specified by size.

Hashtable(int size, float fillratio) //This 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, 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.

Hashtable(Map< ? extends K, ? extends V> m) //This


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.
Example of Hashtable

import java.util.*;

class HashTableDemo

public static void main(String args[])

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

ht.put("a",new Integer(100));

ht.put("b",new Integer(200));

ht.put("c",new Integer(300));

ht.put("d",new Integer(400));

Set st = ht.entrySet();

Iterator itr=st.iterator();

while(itr.hasNext())

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

System.out.println(m.getKey()+" "+m.getValue());

}
a 100

b 200

c 300

d 400

Difference between HashMap and Hashtable

Hashtable HashMap

Hashtable class is synchronized. HashMap is not synchronized.

Because of Thread-safe, Hashtable is slower


HashMap works faster.
than HashMap

Neither key nor values can be null Both key and values can be null

does not guarantee that order of map will rem


Order of table remain constant over time.
constant over time.

Properties class
1. Properties class extends Hashtable class.

2. It is used to maintain list of value in which both key and value are String
3. Properties class define two constructor

Properties() //This creates a Properties object that


has no default values

Properties(Properties propdefault) //This creates an


object that uses propdefault for its default values.

One advantage of Properties over Hashtable is that we can specify a


default property that will be useful when no value is associated with a
certain key.

Note: In both cases, the property list is empty

In Properties class, you can specify a default property that will be


returned if no value is associated with a certain key.

Example of Properties class

import java.util.*;

public class Test

public static void main(String[] args)

{
Properties pr = new Properties();

pr.put("Java", "James Ghosling");

pr.put("C++", "Bjarne Stroustrup");

pr.put("C", "Dennis Ritchie");

pr.put("C#", "Microsoft Inc.");

Set< ?> creator = pr.keySet();

for(Object ob: creator)

System.out.println(ob+" was created by "+


pr.getProperty((String)ob) );

Java was created by James Ghosling

C++ was created by Bjarne Stroustrup

C was created by Dennis Ritchie

C# was created by Microsoft Inc

Stack class

1. Stack class extends Vector.

2. It follows last-in, first-out principle for the stack elements.


3. It defines only one default constructor

Stack() //This creates an empty stack

4. If you want to put an object on the top of the stack, call push() method.
If you want to remove and return the top element, call pop() method. An
EmptyStackException is thrown if you call pop() method when the
invoking stack is empty.

You can use peek() method to return, but not remove, the top object. The
empty() method returns true if nothing is on the stack. The search() method
determines whether an object exists on the stack and returns the number of
pops that are required to bring it to the top of the stack.

Example of Stack

import java.util.*;

class StackDemo {

public static void main(String args[]) {

Stack st = new Stack();

st.push(11);

st.push(22);

st.push(33);

st.push(44);

st.push(55);

Enumeration e1 = st.elements();

while(e1.hasMoreElements())
System.out.print(e1.nextElement()+" ");

st.pop();

st.pop();

System.out.println("\nAfter popping out two elements");

Enumeration e2 = st.elements();

while(e2.hasMoreElements())

System.out.print(e2.nextElement()+" ");

11 22 33 44 55

After popping out two elements

11 22 33

Dictionary class
1. Dictionary is an abstract class.

2. It represents a key/value pair and operates much like Map.

3. Although it is not currently deprecated, Dictionary is classified as


obsolete, because it is fully superseded by Map class.
Generics
Before Generics:
LinkedList l=new LinkedList();
l.add(new Integer(30));
Integer i=(Integer)l.get(0);

After Generics:
LinkedList<Integer> l=new LinkedList<Integer>();
l.add(new Integer(30));
Integer i=l.get(0);

LinkedList<Integer> l=new LinkedList<Integer>();


l.add(new Integer(30));
l.add(new String(“Hai”)); // Compile Time Errror
Integer i=l.get(0);

Generic class can have multiple type parameters


HashMap<String,Integer> l=new
HashMap<String,Integer>();
l.put("one", 10);
l.put(10,"ten"); // Compile Time Error
Defining Generic class
public class demo<F ,S> {
F first;
S second;
demo(F f,S s){
first=f; second=s;
}
void display(){
System.out.println("First value:"+first);
System.out.println("Second value:"+second);
}
public static void main(String [] args)
{
Integer obj=new Integer(10);
String s=new String("Hai");
demo<Integer,String> d=new
demo<Integer,String>(obj,s);
d.display();
demo<Float,Character> d1=new
demo<Float,Character>(new Float(12.34),new
Character('C'));
d1.display();
}
}

Extending the Generic Classes

class one<F,S>{
F first;
S second;
one(F f,S s){
first= f; second=s;

}
}
class two<F,S,T> extends one<F,S>{
T third;
two(F f,S s,T t){
super(f,s);
third=t;
}
void show(){
System.out.println("First value:"+first);
System.out.println("First value:"+second);
System.out.println("First value:"+third);
}
}
public class demo {

public static void main(String [] args)


{
two obj=new two(new Integer(10),new
String("hai"),new demo());
obj.show();
}
}

You might also like