Collections in Java2
Collections in Java2
Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
Let us see the hierarchy of collection [Link] [Link] package contains all the classes
and interfaces for Collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
public boolean is used to delete all the elements of specified collection from
4
removeAll(Collection c) the invoking collection.
public boolean retainAll(Collection is used to delete all the elements of invoking collection except
5
c) the specified collection.
6 public int size() return the total number of elements in the collection.
7 public void clear() removes the total no of element from the collection.
public boolean
9 is used to search the specified collection in this collection.
containsAll(Collection c)
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
void add(int index,Object It is used to insert element into the invoking list at the index passed in
element) the index.
boolean addAll(int It is used to insert all elements of c into the invoking list at the index
index,Collection c) passed in the index.
It is used to return the object stored at the specified index within the
object get(int index)
invoking collection.
object set(int index,Object It is used to assign element to the location specified by index within the
element) invoking list.
It is used to remove the element at position index from the invoking list
object remove(int index)
and return the deleted element.
ListIterator listIterator() It is used to return an iterator to the start of the invoking list.
ListIterator listIterator(int It is used to return an iterator to the invoking list that begins at the
index) specified index.
Java List Example
1. import [Link].*;
2. public class ListExample{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. [Link]("Amit");
6. [Link]("Vijay");
7. [Link]("Kumar");
8. [Link](1,"Sachin");
9. [Link]("Element at 2nd position: "+[Link](2));
10. for(String s:al){
11. [Link](s);
12. }
13. }
14. }
Output:
ListIterator Interface is used to traverse the element in backward and forward direction.
This method return true if the list iterator has more elements when traversing the
boolean hasNext()
list in the forward direction.
Object next() This method return the next element in the list and advances the cursor position.
boolean This method return true if this list iterator has more elements when traversing the
hasPrevious() list in the reverse direction.
Object previous() This method return the previous element in the list and moves the cursor position
backwards.
1. import [Link].*;
2. public class TestCollection8{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. [Link]("Amit");
6. [Link]("Vijay");
7. [Link]("Kumar");
8. [Link](1,"Sachin");
9. [Link]("element at 2nd position: "+[Link](2));
10. ListIterator<String> itr=[Link]();
11. [Link]("traversing elements in forward direction...");
12. while([Link]()){
13. [Link]([Link]());
14. }
15. [Link]("traversing elements in backward direction...");
16. while([Link]()){
17. [Link]([Link]());
18. }
19. }
20. }
Test it Now
Output:
1. import [Link].*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. [Link] = id;
8. [Link] = name;
9. [Link] = author;
10. [Link] = publisher;
11. [Link] = quantity;
12. }
13. }
14. public class ListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. [Link](b1);
24. [Link](b2);
25. [Link](b3);
26. //Traversing list
27. for(Book b:list){
28. [Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);
29. }
30. }
31. }
Output:
Set
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.
List can contain duplicate elements whereas Set contains unique elements only.
Java ArrayList class
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.
As shown in above diagram, Java ArrayList class extends AbstractList class which implements
List interface. The List interface extends Collection and Iterable interfaces in hierarchical order.
It is used to build an array list that is initialized with the elements of the
ArrayList(Collection c)
collection c.
ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.
void add(int index, Object It is used to insert the specified element at the specified position index in a
element) list.
It is used to append all of the elements in the specified collection to the end
boolean addAll(Collection
of this list, in the order that they are returned by the specified collection's
c)
iterator.
void clear() It is used to remove all of the elements from this list.
It is used to return the index in this list of the last occurrence of the
int lastIndexOf(Object o)
specified element, or -1 if the list does not contain this element.
It is used to return an array containing all of the elements in this list in the
Object[] toArray()
correct order.
It is used to return an array containing all of the elements in this list in the
Object[] toArray(Object[] a)
correct order.
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean addAll(int index, It is used to insert all of the elements in the specified collection into this list,
Collection c) starting at the specified position.
It is used to return the index in this list of the first occurrence of the
int indexOf(Object o)
specified element, or -1 if the List does not contain this element.
1. import [Link].*;
2. class TestCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. [Link]("Ravi");//Adding object in arraylist
6. [Link]("Vijay");
7. [Link]("Ravi");
8. [Link]("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=[Link]();
11. while([Link]()){
12. [Link]([Link]());
13. }
14. }
15. }
output
Ravi
Vijay
Ravi
Ajay
Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data
structure. It inherits the AbstractList class and implements List and Deque interfaces.
As shown in above diagram, Java LinkedList class extends AbstractSequentialList class and
implements List and Deque interfaces.
In case of doubly linked list, we can add or remove elements from both side.
LinkedList(Collection It is used to construct a list containing the elements of the specified collection, in
c) the order they are returned by the collection's iterator.
void add(int index, Object It is used to insert the specified element at the specified position index in a
element) list.
void addFirst(Object o) It is used to insert the given element at the beginning of a list.
void addLast(Object o) It is used to append the given element to the end of a list.
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean contains(Object o) It is used to return true if the list contains a specified element.
boolean remove(Object o) It is used to remove the first occurence of the specified element in a list.
It is used to return the index in a list of the first occurrence of the specified
int indexOf(Object o)
element, or -1 if the list does not contain any element.
It is used to return the index in a list of the last occurrence of the specified
int lastIndexOf(Object o)
element, or -1 if the list does not contain any element.
1. import [Link].*;
2. public class TestCollection7{
3. public static void main(String args[]){
4.
5. LinkedList<String> al=new LinkedList<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10.
11. Iterator<String> itr=[Link]();
12. while([Link]()){
13. [Link]([Link]());
14. }
15. }
16. }
Test it Now
Output:Ravi
Vijay
Ravi
Ajay
1. import [Link].*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. [Link] = id;
8. [Link] = name;
9. [Link] = author;
10. [Link] = publisher;
11. [Link] = quantity;
12. }
13. }
14. public class LinkedListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new LinkedList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. [Link](b1);
24. [Link](b2);
25. [Link](b3);
26. //Traversing list
27. for(Book b:list){
28. [Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);
29. }
30. }
31. }
Output:
List can contain duplicate elements whereas Set contains unique elements only.
The HashSet class extends AbstractSet class which implements Set interface. The Set interface
inherits Collection and Iterable interfaces in hierarchical order.
HashSet(Collection
It is used to initialize the hash set by using the elements of the collection c.
c)
HashSet(int It is used to initialize the capacity of the hash set to the given integer value
capacity) capacity. The capacity grows automatically as elements are added to the HashSet.
void clear() It is used to remove all of the elements from this set.
boolean contains(Object
It is used to return true if this set contains the specified element.
o)
boolean add(Object o) It is used to adds the specified element to this set if it is not already present.
boolean remove(Object
It is used to remove the specified element from this set if it is present.
o)
Iterator iterator() It is used to return an iterator over the elements in this set.
1. import [Link].*;
2. class TestCollection9{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10. //Traversing elements
11. Iterator<String> itr=[Link]();
12. while([Link]()){
13. [Link]([Link]());
14. }
15. }
16. }
Test it Now
Ajay
Vijay
Ravi
Let's see a HashSet example where we are adding books to set and printing all the books.
1. import [Link].*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. [Link] = id;
8. [Link] = name;
9. [Link] = author;
10. [Link] = publisher;
11. [Link] = quantity;
12. }
13. }
14. public class HashSetExample {
15. public static void main(String[] args) {
16. HashSet<Book> set=new HashSet<Book>();
17. //Creating Books
18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
19. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
21. //Adding Books to HashSet
22. [Link](b1);
23. [Link](b2);
24. [Link](b3);
25. //Traversing HashSet
26. for(Book b:set){
27. [Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);
28. }
29. }
30. }
Output:
As shown in the above diagram, the Java TreeSet class implements the NavigableSet interface.
The NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in
hierarchical order.
It is used to build a new tree set that contains the elements of the
TreeSet(Collection<? extends E> c)
collection c.
TreeSet(Comparator<? super E> It is used to construct an empty tree set that will be sorted according
comparator) to given comparator.
NavigableSet headSet(E toElement, boolean It returns the group of elements that are less than or
inclusive) equal to(if, inclusive is true) the specified element.
NavigableSet subSet(E fromElement, boolean It returns a set of elements that lie between the given
fromInclusive, E toElement, boolean toInclusive) range.
SortedSet subSet(E fromElement, E toElement)) It returns a set of elements that lie between the given
range which includes fromElement and excludes
toElement.
NavigableSet tailSet(E fromElement, boolean It returns a set of elements that are greater than or
inclusive) equal to (if, inclusive is true) the specified element.
void clear() It is used to remove all of the elements from this set.
FileName: [Link]
1. import [Link].*;
2. class TreeSet1{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> al=new TreeSet<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10. //Traversing elements
11. Iterator<String> itr=[Link]();
12. while([Link]()){
13. [Link]([Link]());
14. }
15. }
16. }
Test it Now
Output:
Ajay
Ravi
Vijay
FileName: [Link]
1. import [Link].*;
2. class TreeSet2{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. [Link]("Ravi");
6. [Link]("Vijay");
7. [Link]("Ajay");
8. [Link]("Traversing element through Iterator in descending order");
9. Iterator i=[Link]();
10. while([Link]())
11. {
12. [Link]([Link]());
13. }
14.
15. }
16. }
Test it Now
Output:
Let's see an example to retrieve and remove the highest and lowest Value.
FileName: [Link]
1. import [Link].*;
2. class TreeSet3{
3. public static void main(String args[]){
4. TreeSet<Integer> set=new TreeSet<Integer>();
5. [Link](24);
6. [Link](66);
7. [Link](12);
8. [Link](15);
9. [Link]("Lowest Value: "+[Link]());
10. [Link]("Highest Value: "+[Link]());
11. }
12. }
Output:
Lowest Value: 12
Highest Value: 66
FileName: [Link]
1. import [Link].*;
2. class TreeSet4{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. [Link]("A");
6. [Link]("B");
7. [Link]("C");
8. [Link]("D");
9. [Link]("E");
10. [Link]("Initial Set: "+set);
11.
12. [Link]("Reverse Set: "+[Link]());
13.
14. [Link]("Head Set: "+[Link]("C", true));
15.
16. [Link]("SubSet: "+[Link]("A", false, "E", true));
17.
18. [Link]("TailSet: "+[Link]("C", false));
19. }
20. }
Output:
1. import [Link].*;
2. class TreeSet5{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. [Link]("A");
6. [Link]("B");
7. [Link]("C");
8. [Link]("D");
9. [Link]("E");
10.
11. [Link]("Intial Set: "+set);
12.
13. [Link]("Head Set: "+[Link]("C"));
14.
15. [Link]("SubSet: "+[Link]("A", "E"));
16.
17. [Link]("TailSet: "+[Link]("C"));
18. }
19. }
Output:
Let's see a TreeSet example where we are adding books to the set and printing all the books. The
elements in TreeSet must be of a Comparable type. String and Wrapper classes are Comparable
by default. To add user-defined objects in TreeSet, you need to implement the Comparable
interface.
FileName: [Link]
1. import [Link].*;
2. class Book implements Comparable<Book>{
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. [Link] = id;
8. [Link] = name;
9. [Link] = author;
10. [Link] = publisher;
11. [Link] = quantity;
12. }
13. // implementing the abstract method
14. public int compareTo(Book b) {
15. if(id>[Link]){
16. return 1;
17. }else if(id<[Link]){
18. return -1;
19. }else{
20. return 0;
21. }
22. }
23. }
24. public class TreeSetExample {
25. public static void main(String[] args) {
26. Set<Book> set=new TreeSet<Book>();
27. //Creating Books
28. Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
29. Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
30. Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
If we add an object of the class that is not implementing the Comparable interface, the ClassCast
Exception is raised. Observe the following program.
FileName: [Link]