You are on page 1of 20

B. P.

Poddar Institute of Management and Technology


Department of Computer Science & Engineering

Term Paper /Micro-project Details

Paper Name: Object Oriented Programming Code: PCC-CS503

Term Paper/Micro-project Title: Java Collections Framework

Student Details:

Name University Roll No.


Shubham Kumar Mishra 11500119005
Taufique Raza 11500119029
Sneha Tiwari 11500119052
Shivam Seksaria 11500119060

<Please do not write anything below the dotted line>


………………………………………………………………………

Marks awarded

Marks Awarded

Total Marks

Signature of Faculty with date…………………………………………


Abstract
The Collections Framework comprises one of the most important subsystems
in the Java API. Collections are sometimes called "containers" and provide
support for a variety of data structures: stacks, queues, dynamic arrays, and
linked lists. The java.util package houses most of the Collections Framework
including
1. Interfaces - the abstract data types (ADT's) that represent
collections
2. Implementations - data structures like ArrayList that are the
concrete implementations of the interfaces
3. Algorithms - polymorphic methods like "sort()" that work on
many different containers and which standardize the approach to
processing a collection. These methods are packaged as static
methods
The top level of the interface hierarchy is Collection.
A standard way to cycle through the elements of a collection is with
an Iterator object. All Collections implement the Iterator interface and as a
result, it is easy to cycle through the objects in a Collection with a for-each
loop.
The Collection interface provides functionality to all collections and all classes
that define a collection class implement this interface.
Contents
 Introduction

 Lists

o ArrayList

o LinkedList

 Queues

 Sets

 Maps

 Analysis

 Conclusion

 References
Introduction
A collection is a data structure - actually an object – that can hold references to
other objects. Usually, collections contain references to objects of any type that
has the is-a relationship with the collection’s element type. The collections-
framework interfaces declare the operations to be performed generically on
various types of collections.
Interface Collection contains bulk operations(i.e., operations performed on an
entire collection) for operations such as adding, clearing, and comparing objects
(or elements) in a collection. A Collection can also be converted to an array. In
addition, interface Collection provides a method that returns an Iterator object,
which allows a program to walk through the collection and remove elements
from it during the iteration.
The Collections Framework Hierarchy
Lists
A List is a Collection of elements in sequence that can contain duplicate
elements. Like array indices, List indices are zero based (i.e., the first element’s
index is zero). In addition to the methods inherited from Collection, List
provides methods for manipulating elements via their indices, manipulating a
specified range of elements, searching for elements obtaining a ListIterator to
access the elements.
Interface List is implemented by several classes, including ArrayList and
LinkedList. Autoboxing occurs when we add primitive-type values to objects of
these classes, because they store only references to objects.
ArrayList
Below program uses an ArrayList to demonstrate several capabilities of
interfaces Collection. The program places two Color arrays in ArrayLists and
uses an Iterator to remove elements in the second ArrayList collection from the
first.
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionTest{
public static void main(String args[]){
String[] colors = {“Magenta”, “Red”, “White”, “Blue”, “Cyan”};
List<String> list = new ArrayList<String>();
for(String color: colors){
list.add(color);
}
String[] removeColors = {“Red”, “White”, “Blue”};
List<String> removeList = new ArrayList<String>();
for(String color: colors){
removeList.add(color);
}
System.out.println(“ArrayList: ”);
for(int count=0; count<list.size(); count++){
System.out.printf(“%s”, list.get(count));
}
removeColors(list, removeList);
System.out.printf(“%n%nArrayList after calling removeColors:
%n”);
for(String color: list){
System.out.printf(“%s”, color);
}
}
private static void removeColors(Collections<String> collection1,
Collections<String> collection2){
Iterator<String> iterator = collection.iterator();
while(iterator.hasNext()){
if(collection2.contain(iterator.next()){
iterator.remove();
}
}
}
}

Output:
ArrayList:
MAGENTA RED WHITE BLUE CYAN
ArrayList after calling removeColors:
MAGENTA CYAN
LinkedList
Below program demonstrates various operations on LimkedLists. The program
creates two LinkedLists of Strings. The elements of one LinkedList are added to
the other. Then all the Strings are converted to uppercase and a range of
elements is deleted.
import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;
public class ListTest{
public static void main(String[] args){
String[] colors = {“black”, “yellow”, “green”, “blue”, “violet”,
“silver”};
List<String> list1 = new LinkedList<>();
for(String color: colors){
list1.add(color);
}
String[] colors2 = {“gold”, “silver”, “white”, “brown”, “blue”,
“gray”};
List<String> list2 = new LinkedList<>();
for(String color: colors2){
list2.add(color);
}
list1.addAll(list2);
list2 = null;
printList(list2);
convertToUppercaseStrings(list1);
printList(list1);
System.out.printf(“Deleting elements 4 to 6…”);
removeItems(list1, 4, 7);
printList(list1);
printReversedList(list1);
}
private static void printList(List<String> list){
System.out.printf(“%nlist:%n”);
for(String color: list){
System.out.printf(“%s ”, color);
}
System.out.println();
}
private static void convertToUppercaseString(List<String> list){
ListIterator<String> iterator = list.listIterator();
while(iterator.hasNext()){
String color = iterator.next();
iterator.set(color.toUpperCase());
}
}
private static void removeItems(List<String> list, int start, int end){
list.subList(start, end).clear();
}
private static void printReversedList(List<String> list){
ListIterator<String> iterator = list.listIterator(list.size());
System.out.printf(“%nReversed List:%n”);
while(iterator.hasPrevious()){
System.out.printf(“%s ”, iterator.previous());
}
}
}
Output:

list:
black yellow green blue violet silver gold white brown blue gray silver

list:
BLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE
GRAY SILVER

Deleting elements 4 to 6…
list:
BLACK YELLOW GREEN BLUE WHITE BROWN BLUE GRAY SILVER

Reversed List:
SILVER GRAY BLUE BROWN WHITE BLUE GREEN YELLOW BLACK
Queues
A Queue is a collection that represents a waiting line, typically, insertions are
made at the back of a queue and deletions are made from the front. Interface
Queue extends interface Collection and provides additional operations for
inserting, removing and inspecting elements in a queue. PriorityQueue, which
implements the Queue interface, orders elements by their natural ordering as
specified by Comparable elements’ compareTo method or by a Comparator
object that’s supplied to the constructor.
Class PriorityQueue provides functionality that enables insertions in sorted
order into the underlying data structure and deletions from the front of the
underlying data structure. When adding elements to the PriorityQueue, the
elements are inserted in priority order such that the highest priority element(i.e.,
the largest value) will be the first element removed from the PriorityQueue.
The common PriorityQueue operations are offer to insert at the appropriate
location based on priority order, poll to remove the highest-priority element of
the priority queue(i.e., the head of the queue), peek to get a reference to the
highest-priority element of the priority queue(without removing the element),
clear to remove all elements of the priority queue and size to get the number of
elements in the priority queue.
Below program demonstrate a Priority Queue:
import java.util.PriorityQueue;
public class PriorityQueueTest{
public static void main(String[] args){
PriorityQueue<double> queue = new PriorityQueue<>();
queue.offer(3.2);
queue.offer(9.8);
queue.offer(5.4);
System.out.print(“Polling elements from queue: ”);
while(queue.size() > 0){
System.out.printf(“%.1f ”, queue.peek());
queue.poll();
}
}
}

Output:

Polling from queue: 3.2 5.4 9.8


Sets
A Set is a collection of unique elements (i.e., no duplicates). The collections
framework contains several Set implementations, including HashSet and
TreeSet. HashSet stores its elements (unordered) in a hash table and TreeSet
stores its elements (ordered) in a tree.
Below is a program that uses HashSet to remove duplicate strings from a list:
import java.util.List;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.Collection;
public class SetTest{
public static void main(String[] args){
String[] colors = {“red”, “white”, “blue”, “green”, “gray”,
“orange”, “tan”, “white”, “cyan”, “peach”, “gray”, “orange”};
List<String> list = Arrays.asList(colors);
System.out.printf(“List: %s%n”, list);
printNonDuplicates(list);
}
private static void printNonDuplicates(Collection<String> values){
Set<String> set = new HashSet<>(values);
System.out.printf(“%nNonduplicates are: ”);
for(String value: set){
System.out.printf(“%s ”, value);
}
System.out.println();
}
}
Output:
List: [ red, white, blue, green, gray, orange, tan, white, cyan, peach, gray,
orange ]
Nonduplicates are: tan green peach cyan red orange gray white blue

SortedSet
The collections framework also includes the SortedSet interface(which extends
Set) for sets that maintain their elements in sorted order – either the elements’
natural order(e.g., numbers are in ascending order) or an order specified by the
Comparator. Class TreeSet implements SortedSet.
Below program demonstrates the use of TreeSet and SortedSet:
import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;
public class SortedSetTest{
public static void main(String[] args){
String[] colors = {“yellow”, “green”, “black”, “tan”, “grey”,
“white”, “orange”, “red”, “green”};
SortedSet<String> tree = new TreeSet<>(Arrays.asList(colors));
System.out.print(“Sorted set: ”);
printSet(tree);
System.out.print(“headSet (\”orange\”): “);
printSet(tree.headSet(“orange”);
System.out.print(“tailSet (\”orange\”): “);
System.out.printf(“first: %s%n”, tree.first());
System.out.printf(“last: %s%n”, tree.last());
}
private static void printSet(SortedSet<String> set){
for(String s: set){
System.out.print(“%s “, s);
}
System.out.println();
}
}

Output:
sorted set: black green gray orange red tan white yellow
headSet (“orange”): black green gray
tailSet (“orange”): orange red tan white yellow
first: black
last: yellow
Maps
Maps associate keys to values. The keys in a Map must be unique, but the
associated values need not be. If a Map contains both unique keys and unique
values, it’s said to implement a one-to-one mapping. If only the keys are unique,
the Map is said to implement a many-to-one mapping – many keys can map to
one value.
Map differs from Sets in that Maps contain keys and values, whereas Sets
contain only values. Two classes that implement interface Map are HashMap
and TreeMap. HashMaps store elements in hash table and TreeMaps store
elements in trees. Interface SortedMap extends Map and maintains its keys in
sorted order – either the elements’ natural order or an order specified by a
Comparator. Class TreeMap implements SortedMap.
Below program demonstrates the use of Maps:
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.Scanner;
public class WordTypeCount{
public static void main(String[] args){
Map<String, Integer> myMap = new Hashmap<>();
createMap(myMap);
displayMap(myMap);
}
private static void createMap(Map<String, Integer> map){
Scanner scanner = new Scanner(System.in);
System.out.println(“Enter a string: “);
String input = scanner.nextLine();
String[] tokens = input.split(“ “);
for(String token: tokens){
String word = token.toLowerCase();
if(map.containsKey(word)){
int count = map.get(word);
map.put(word, count+1);
}
Else{
map.put(word, 1);
}
}
}
public static void displayMap(Map<String, Integer> map){
Set<String> keys = map.keySet();
TreeSet<String> sortedKeys = new TreeSet<>(keys);
System.out.print(“%nMap contains:%nKey\t\tValue%n”);
for(String key: sortedKeys){
System.out.printf(“%-10s%10s%n”, key, map.get(key));
}
System.out.printf(“%nsize: %d%nisEmpty: %b%n”, map.size(),
map.isEmpty());
}
}

Output:
Enter a string:
this is a sample sentence with several words this is another sample sentence
with several different words

Map contains:
Key Value
a 1
another 1
different 1
is 2
sample 2
sentence 2
several 2
this 2
with 2
words 2

size: 10
isEmpty: false
Analysis
Advantages of Collection framework:
 Consistent API: The API has a basic set of interfaces like Collection,
Set, List, or Map, all the classes (ArrayList, LinkedList, Vector, etc) that
implement these interfaces have some common set of methods.
 Reduces programming effort: A programmer doesn’t have to worry
about the design of the Collection but rather he can focus on its best use
in his program. Therefore, the basic concept of Object-oriented
programming (i.e.) abstraction has been successfully implemented.
 Increases program speed and quality: Increases performance by
providing high-performance implementations of useful data structures
and algorithms because in this case, the programmer need not think of the
best implementation of a specific data structure. He can simply use the
best implementation to drastically boost the performance of his
algorithm/program.

Disadvantages of Collection framework:


 It must be cast to correct type.
 Compile-time type checking can’t be done.
Conclusion
Hence, in this term paper we have studied about Collections framework. We
have the studied the need for Collections framework. We have seen the
hierarchy of collections framework in Java. We have also seen different types of
classes and interfaces provided by the framework and also discussed few of the
important ones. The collections framework helps to avoid reinventing the wheel
i.e., rather than building our own data structure we can use the classes and
interfaces provided by the framework which has been carefully tested and fine
tuned to meet out application needs. After that we did an analysis and discussed
some of the advantages and disadvantages of the collections framework.
The Java collection framework is very powerful and includes numerous
capabilities not mentioned in this article, such as cloning, return values,
removing elements, and more. All of these features are well described in the
JDK documentation, and one can refer to them as you become more familiar
with this rich set of classes.
References
The following books and websites have been used as a reference to make this
term paper:
Books:
 Java: How to program (Pearson Publication) by Harvey Deitel and Paul
Deitel

Websites:
 www.javatpoint.com

You might also like