Professional Documents
Culture Documents
Student Details:
Marks awarded
Marks Awarded
Total Marks
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:
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.
Websites:
www.javatpoint.com