COMP 213 Advanced Object-oriented Programming Lecture 12 Java - - PowerPoint PPT Presentation

comp 213
SMART_READER_LITE
LIVE PREVIEW

COMP 213 Advanced Object-oriented Programming Lecture 12 Java - - PowerPoint PPT Presentation

COMP 213 Advanced Object-oriented Programming Lecture 12 Java Collections. The Collections Framework Unified architecture for representing and manipulating collections. Enables collections to be manipulated independently of the details


slide-1
SLIDE 1

COMP 213

Advanced Object-oriented Programming Lecture 12 Java Collections.

slide-2
SLIDE 2

The Collections Framework

  • Unified architecture for representing and manipulating collections.
  • Enables collections to be manipulated independently of the details of their

representation.

  • Based on more than a dozen collection interfaces.
  • Includes implementations of these interfaces and algorithms to manipulate

them.

slide-3
SLIDE 3

Overview

A collection is an object that represents a group of objects (such as the classic Vector class). Primary advantages of a collections framework:

  • Reduces programming effort (provides data structures & algorithms)
  • Increases performance (provides high-performance implementations of data

structures & algorithms)

  • Provides interoperability between unrelated APIs (establishes a common

language to pass collections back and forth)

  • Fosters software reuse (provides a standard interface for collections & algorithms

with which to manipulate them)

slide-4
SLIDE 4

Overview

A collection is an object that represents a group of objects (such as the classic Vector class). Primary advantages of a collections framework:

  • Reduces programming effort (provides data structures & algorithms)
  • Increases performance (provides high-performance implementations of data

structures & algorithms)

  • Provides interoperability between unrelated APIs (establishes a common

language to pass collections back and forth)

  • Fosters software reuse (provides a standard interface for collections & algorithms

with which to manipulate them)

slide-5
SLIDE 5

Overview

A collection is an object that represents a group of objects (such as the classic Vector class). Primary advantages of a collections framework:

  • Reduces programming effort (provides data structures & algorithms)
  • Increases performance (provides high-performance implementations of data

structures & algorithms)

  • Provides interoperability between unrelated APIs (establishes a common

language to pass collections back and forth)

  • Fosters software reuse (provides a standard interface for collections & algorithms

with which to manipulate them)

slide-6
SLIDE 6

Overview

A collection is an object that represents a group of objects (such as the classic Vector class). Primary advantages of a collections framework:

  • Reduces programming effort (provides data structures & algorithms)
  • Increases performance (provides high-performance implementations of data

structures & algorithms)

  • Provides interoperability between unrelated APIs (establishes a common

language to pass collections back and forth)

  • Fosters software reuse (provides a standard interface for collections & algorithms

with which to manipulate them)

slide-7
SLIDE 7

Overview

A collection is an object that represents a group of objects (such as the classic Vector class). Primary advantages of a collections framework:

  • Reduces programming effort (provides data structures & algorithms)
  • Increases performance (provides high-performance implementations of data

structures & algorithms)

  • Provides interoperability between unrelated APIs (establishes a common

language to pass collections back and forth)

  • Fosters software reuse (provides a standard interface for collections & algorithms

with which to manipulate them)

slide-8
SLIDE 8

The collections framework consists of:

  • Collection interfaces. Represent different types of collections, such as sets, lists, and
  • maps. These interfaces form the basis of the framework.
  • General-purpose implementations. Primary implementations of the collection interfaces.
  • Legacy implementations. The collection classes from earlier releases, Vector and

Hashtable, were retrofitted to implement the collection interfaces.

  • Algorithms. Static methods that perform useful functions on collections, such as sorting a

list.

  • Other implementations, e.g., Concurrent, Wrapper, Convenience, and Abstract

implementations.

slide-9
SLIDE 9

The collections framework consists of:

  • Collection interfaces. Represent different types of collections, such as sets, lists, and
  • maps. These interfaces form the basis of the framework.
  • General-purpose implementations. Primary implementations of the collection interfaces.
  • Legacy implementations. The collection classes from earlier releases, Vector and

Hashtable, were retrofitted to implement the collection interfaces.

  • Algorithms. Static methods that perform useful functions on collections, such as sorting a

list.

  • Other implementations, e.g., Concurrent, Wrapper, Convenience, and Abstract

implementations.

slide-10
SLIDE 10

The collections framework consists of:

  • Collection interfaces. Represent different types of collections, such as sets, lists, and
  • maps. These interfaces form the basis of the framework.
  • General-purpose implementations. Primary implementations of the collection interfaces.
  • Legacy implementations. The collection classes from earlier releases, Vector and

Hashtable, were retrofitted to implement the collection interfaces.

  • Algorithms. Static methods that perform useful functions on collections, such as sorting a

list.

  • Other implementations, e.g., Concurrent, Wrapper, Convenience, and Abstract

implementations.

slide-11
SLIDE 11

The collections framework consists of:

  • Collection interfaces. Represent different types of collections, such as sets, lists, and
  • maps. These interfaces form the basis of the framework.
  • General-purpose implementations. Primary implementations of the collection interfaces.
  • Legacy implementations. The collection classes from earlier releases, Vector and

Hashtable, were retrofitted to implement the collection interfaces.

  • Algorithms. Static methods that perform useful functions on collections, such as sorting a

list.

  • Other implementations, e.g., Concurrent, Wrapper, Convenience, and Abstract

implementations.

slide-12
SLIDE 12

The collections framework consists of:

  • Collection interfaces. Represent different types of collections, such as sets, lists, and
  • maps. These interfaces form the basis of the framework.
  • General-purpose implementations. Primary implementations of the collection interfaces.
  • Legacy implementations. The collection classes from earlier releases, Vector and

Hashtable, were retrofitted to implement the collection interfaces.

  • Algorithms. Static methods that perform useful functions on collections, such as sorting a

list.

  • Other implementations, e.g., Concurrent, Wrapper, Convenience, and Abstract

implementations.

slide-13
SLIDE 13

Collection Interfaces

Divided into two groups:

  • java.util.Collection (the most basic interface), and
  • java.util.Map (not true collections, but contain collection-view operations,

which enable them to be manipulated as collections.

slide-14
SLIDE 14

Collection Interfaces

Divided into two groups:

  • java.util.Collection (the most basic interface), and
  • java.util.Map (not true collections, but contain collection-view operations,

which enable them to be manipulated as collections.

slide-15
SLIDE 15

java.util.Collection

  • Collection - A group of objects. No assumptions are made about the order of the collection (if

any) or whether it can contain duplicate elements.

  • Set -The familiar set abstraction. No duplicate elements permitted. May or may not be ordered.
  • SortedSet - A set whose elements are automatically sorted, either in their natural ordering or by

a comparator provided when a SortedSet instance is created.

  • List - Ordered collection, also known as a sequence. Duplicates are generally permitted. Allows

positional access.

  • Queue - A collection designed for holding elements before processing. Besides basic Collection
  • perations, queues provide additional insertion, extraction, and inspection operations.
  • Deque - A double ended queue, supporting element insertion and removal at both ends.
slide-16
SLIDE 16

java.util.Collection

  • Collection - A group of objects. No assumptions are made about the order of the collection (if

any) or whether it can contain duplicate elements.

  • Set -The familiar set abstraction. No duplicate elements permitted. May or may not be ordered.
  • SortedSet - A set whose elements are automatically sorted, either in their natural ordering or by

a comparator provided when a SortedSet instance is created.

  • List - Ordered collection, also known as a sequence. Duplicates are generally permitted. Allows

positional access.

  • Queue - A collection designed for holding elements before processing. Besides basic Collection
  • perations, queues provide additional insertion, extraction, and inspection operations.
  • Deque - A double ended queue, supporting element insertion and removal at both ends.
slide-17
SLIDE 17

java.util.Collection

  • Collection - A group of objects. No assumptions are made about the order of the collection (if

any) or whether it can contain duplicate elements.

  • Set -The familiar set abstraction. No duplicate elements permitted. May or may not be ordered.
  • SortedSet - A set whose elements are automatically sorted, either in their natural ordering or by

a comparator provided when a SortedSet instance is created.

  • List - Ordered collection, also known as a sequence. Duplicates are generally permitted. Allows

positional access.

  • Queue - A collection designed for holding elements before processing. Besides basic Collection
  • perations, queues provide additional insertion, extraction, and inspection operations.
  • Deque - A double ended queue, supporting element insertion and removal at both ends.
slide-18
SLIDE 18

java.util.Collection

  • Collection - A group of objects. No assumptions are made about the order of the collection (if

any) or whether it can contain duplicate elements.

  • Set -The familiar set abstraction. No duplicate elements permitted. May or may not be ordered.
  • SortedSet - A set whose elements are automatically sorted, either in their natural ordering or by

a comparator provided when a SortedSet instance is created.

  • List - Ordered collection, also known as a sequence. Duplicates are generally permitted. Allows

positional access.

  • Queue - A collection designed for holding elements before processing. Besides basic Collection
  • perations, queues provide additional insertion, extraction, and inspection operations.
  • Deque - A double ended queue, supporting element insertion and removal at both ends.
slide-19
SLIDE 19

java.util.Collection

  • Collection - A group of objects. No assumptions are made about the order of the collection (if

any) or whether it can contain duplicate elements.

  • Set -The familiar set abstraction. No duplicate elements permitted. May or may not be ordered.
  • SortedSet - A set whose elements are automatically sorted, either in their natural ordering or by

a comparator provided when a SortedSet instance is created.

  • List - Ordered collection, also known as a sequence. Duplicates are generally permitted. Allows

positional access.

  • Queue - A collection designed for holding elements before processing. Besides basic Collection
  • perations, queues provide additional insertion, extraction, and inspection operations.
  • Deque - A double ended queue, supporting element insertion and removal at both ends.
slide-20
SLIDE 20

java.util.Collection

  • Collection - A group of objects. No assumptions are made about the order of the collection (if

any) or whether it can contain duplicate elements.

  • Set -The familiar set abstraction. No duplicate elements permitted. May or may not be ordered.
  • SortedSet - A set whose elements are automatically sorted, either in their natural ordering or by

a comparator provided when a SortedSet instance is created.

  • List - Ordered collection, also known as a sequence. Duplicates are generally permitted. Allows

positional access.

  • Queue - A collection designed for holding elements before processing. Besides basic Collection
  • perations, queues provide additional insertion, extraction, and inspection operations.
  • Deque - A double ended queue, supporting element insertion and removal at both ends.
slide-21
SLIDE 21

java.util.Map

  • Map - A mapping from keys to values. A Map cannot contain duplicate keys;

each key can map to at most one value.

  • SortedMap - a Map that maintains its mappings in ascending key order. This

is the Map analogue of SortedSet. Sorted maps are used for naturally

  • rdered collections of key/value pairs, such as dictionaries and telephone

directories.

slide-22
SLIDE 22

java.util.Map

  • Map - A mapping from keys to values. A Map cannot contain duplicate keys;

each key can map to at most one value.

  • SortedMap - a Map that maintains its mappings in ascending key order. This

is the Map analogue of SortedSet. Sorted maps are used for naturally

  • rdered collections of key/value pairs, such as dictionaries and telephone

directories.

slide-23
SLIDE 23

General-purpose implementations

  • HashSet - Hash table implementation of the Set interface. The best all-around implementation of the Set

interface.

  • TreeSet - Balanced tree implementation of the Set interface.
  • LinkedHashSet - Hash table and linked list implementation of the Set interface. An insertion-ordered Set

implementation that runs nearly as fast as HashSet.

  • ArrayList - Resizable array implementation of the List interface. The best all-around implementation of the

List interface.

  • LinkedList - Doubly-linked list implementation of the List interface. Provides better performance than the

ArrayList implementation if elements are frequently inserted or deleted within the list.

  • HashMap - Hash table implementation of the Map interface. The best all-around implementation of the

Map interface.

  • and many many others…
slide-24
SLIDE 24

General-purpose implementations

  • HashSet - Hash table implementation of the Set interface. The best all-around implementation of the Set

interface.

  • TreeSet - Balanced tree implementation of the Set interface.
  • LinkedHashSet - Hash table and linked list implementation of the Set interface. An insertion-ordered Set

implementation that runs nearly as fast as HashSet.

  • ArrayList - Resizable array implementation of the List interface. The best all-around implementation of the

List interface.

  • LinkedList - Doubly-linked list implementation of the List interface. Provides better performance than the

ArrayList implementation if elements are frequently inserted or deleted within the list.

  • HashMap - Hash table implementation of the Map interface. The best all-around implementation of the

Map interface.

  • and many many others…
slide-25
SLIDE 25

General-purpose implementations

  • HashSet - Hash table implementation of the Set interface. The best all-around implementation of the Set

interface.

  • TreeSet - Balanced tree implementation of the Set interface.
  • LinkedHashSet - Hash table and linked list implementation of the Set interface. An insertion-ordered Set

implementation that runs nearly as fast as HashSet.

  • ArrayList - Resizable array implementation of the List interface. The best all-around implementation of the

List interface.

  • LinkedList - Doubly-linked list implementation of the List interface. Provides better performance than the

ArrayList implementation if elements are frequently inserted or deleted within the list.

  • HashMap - Hash table implementation of the Map interface. The best all-around implementation of the

Map interface.

  • and many many others…
slide-26
SLIDE 26

General-purpose implementations

  • HashSet - Hash table implementation of the Set interface. The best all-around implementation of the Set

interface.

  • TreeSet - Balanced tree implementation of the Set interface.
  • LinkedHashSet - Hash table and linked list implementation of the Set interface. An insertion-ordered Set

implementation that runs nearly as fast as HashSet.

  • ArrayList - Resizable array implementation of the List interface. The best all-around implementation of the

List interface.

  • LinkedList - Doubly-linked list implementation of the List interface. Provides better performance than the

ArrayList implementation if elements are frequently inserted or deleted within the list.

  • HashMap - Hash table implementation of the Map interface. The best all-around implementation of the

Map interface.

  • and many many others…
slide-27
SLIDE 27

General-purpose implementations

  • HashSet - Hash table implementation of the Set interface. The best all-around implementation of the Set

interface.

  • TreeSet - Balanced tree implementation of the Set interface.
  • LinkedHashSet - Hash table and linked list implementation of the Set interface. An insertion-ordered Set

implementation that runs nearly as fast as HashSet.

  • ArrayList - Resizable array implementation of the List interface. The best all-around implementation of the

List interface.

  • LinkedList - Doubly-linked list implementation of the List interface. Provides better performance than the

ArrayList implementation if elements are frequently inserted or deleted within the list.

  • HashMap - Hash table implementation of the Map interface. The best all-around implementation of the

Map interface.

  • and many many others…
slide-28
SLIDE 28

General-purpose implementations

  • HashSet - Hash table implementation of the Set interface. The best all-around implementation of the Set

interface.

  • TreeSet - Balanced tree implementation of the Set interface.
  • LinkedHashSet - Hash table and linked list implementation of the Set interface. An insertion-ordered Set

implementation that runs nearly as fast as HashSet.

  • ArrayList - Resizable array implementation of the List interface. The best all-around implementation of the

List interface.

  • LinkedList - Doubly-linked list implementation of the List interface. Provides better performance than the

ArrayList implementation if elements are frequently inserted or deleted within the list.

  • HashMap - Hash table implementation of the Map interface. The best all-around implementation of the

Map interface.

  • and many many others…
slide-29
SLIDE 29

General-purpose implementations

  • HashSet - Hash table implementation of the Set interface. The best all-around implementation of the Set

interface.

  • TreeSet - Balanced tree implementation of the Set interface.
  • LinkedHashSet - Hash table and linked list implementation of the Set interface. An insertion-ordered Set

implementation that runs nearly as fast as HashSet.

  • ArrayList - Resizable array implementation of the List interface. The best all-around implementation of the

List interface.

  • LinkedList - Doubly-linked list implementation of the List interface. Provides better performance than the

ArrayList implementation if elements are frequently inserted or deleted within the list.

  • HashMap - Hash table implementation of the Map interface. The best all-around implementation of the

Map interface.

  • and many many others…
slide-30
SLIDE 30

General-purpose implementations

Implementations Hash Table Resizable Array Balanced Tree Linked List Hash Table + Linked List Interfaces Set HashSet TreeSet LinkedHashSet List ArrayList, Vector LinkedList Map HashMap

slide-31
SLIDE 31

Class HashSet<E>

  • Doesn’t maintain any order, the elements would be returned in any random
  • rder.
  • Doesn’t allow duplicates. If you try to add a duplicate element in HashSet,

the old value would be overwritten.

  • Allows null values however if you insert more than one nulls it would still

return only one null value.

slide-32
SLIDE 32

HashSet Example

import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // HashSet declaration HashSet<String> hset = new HashSet<String>(); // Adding elements to the HashSet hset.add("Apple"); hset.add("Mango"); hset.add("Grapes"); hset.add("Orange"); hset.add("Fig"); // Addition of duplicate elements hset.add("Apple"); hset.add("Mango"); // Addition of null values hset.add(null); hset.add(null); // Displaying HashSet elements System.out.println(hset); } }

slide-33
SLIDE 33

HashSet Example

import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // HashSet declaration HashSet<String> hset = new HashSet<String>(); // Adding elements to the HashSet hset.add("Apple"); hset.add("Mango"); hset.add("Grapes"); hset.add("Orange"); hset.add("Fig"); // Addition of duplicate elements hset.add("Apple"); hset.add("Mango"); // Addition of null values hset.add(null); hset.add(null); // Displaying HashSet elements System.out.println(hset); } }

slide-34
SLIDE 34

HashSet Example

import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // HashSet declaration HashSet<String> hset = new HashSet<String>(); // Adding elements to the HashSet hset.add("Apple"); hset.add("Mango"); hset.add("Grapes"); hset.add("Orange"); hset.add("Fig"); // Addition of duplicate elements hset.add("Apple"); hset.add("Mango"); // Addition of null values hset.add(null); hset.add(null); // Displaying HashSet elements System.out.println(hset); } }

slide-35
SLIDE 35

HashSet Example

import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // HashSet declaration HashSet<String> hset = new HashSet<String>(); // Adding elements to the HashSet hset.add("Apple"); hset.add("Mango"); hset.add("Grapes"); hset.add("Orange"); hset.add("Fig"); // Addition of duplicate elements hset.add("Apple"); hset.add("Mango"); // Addition of null values hset.add(null); hset.add(null); // Displaying HashSet elements System.out.println(hset); } }

slide-36
SLIDE 36

HashSet Example

import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // HashSet declaration HashSet<String> hset = new HashSet<String>(); // Adding elements to the HashSet hset.add("Apple"); hset.add("Mango"); hset.add("Grapes"); hset.add("Orange"); hset.add("Fig"); // Addition of duplicate elements hset.add("Apple"); hset.add("Mango"); // Addition of null values hset.add(null); hset.add(null); // Displaying HashSet elements System.out.println(hset); } }

slide-37
SLIDE 37

HashSet Example

import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // HashSet declaration HashSet<String> hset = new HashSet<String>(); // Adding elements to the HashSet hset.add("Apple"); hset.add("Mango"); hset.add("Grapes"); hset.add("Orange"); hset.add("Fig"); // Addition of duplicate elements hset.add("Apple"); hset.add("Mango"); // Addition of null values hset.add(null); hset.add(null); // Displaying HashSet elements System.out.println(hset); } }

slide-38
SLIDE 38

HashSet Example

[null, Apple, Grapes, Fig, Mango, Orange]

Output:

slide-39
SLIDE 39

HashSet Methods

  • boolean add(Element e): It adds the element e to the list.
  • void clear(): It removes all the elements from the list.
  • Object clone(): This method returns a shallow copy of the HashSet.
  • boolean contains(Object o): It checks whether the specified Object o is present in the list
  • r not. If the object has been found it returns true else false.
  • boolean isEmpty(): Returns true if there is no element present in the Set.
  • int size(): It gives the number of elements of a Set.
  • boolean remove(Object o): It removes the specified Object o from the Set.
  • For more info: https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
slide-40
SLIDE 40

Class HashMap<K,V>

  • Maintains key and value pairs.
  • Allows null key and null values.
  • Used for maintaining key and value mapping.
  • Not ordered: it does not return the keys and values in the same order in

which they have been inserted.

slide-41
SLIDE 41

HashMap Example

import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.Set; public class HashMapExample { public static void main(String args[]) { HashMap<Integer, String> hmap = new HashMap<Integer, String>(); hmap.put(12, "Eleni"); hmap.put(2, "Thomas"); hmap.put(7, "Bob"); hmap.put(49, "Rahul"); hmap.put(3, "Alice "); // Display content using Iterator Set set = hmap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry mentry = (Map.Entry) iterator.next(); System.out.print("key is: " + mentry.getKey() + " & Value is: "); System.out.println(mentry.getValue()); }

slide-42
SLIDE 42

HashMap Example

import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.Set; public class HashMapExample { public static void main(String args[]) { HashMap<Integer, String> hmap = new HashMap<Integer, String>(); hmap.put(12, "Eleni"); hmap.put(2, "Thomas"); hmap.put(7, "Bob"); hmap.put(49, "Rahul"); hmap.put(3, "Alice "); // Display content using Iterator Set set = hmap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry mentry = (Map.Entry) iterator.next(); System.out.print("key is: " + mentry.getKey() + " & Value is: "); System.out.println(mentry.getValue()); }

slide-43
SLIDE 43

HashMap Example

import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.Set; public class HashMapExample { public static void main(String args[]) { HashMap<Integer, String> hmap = new HashMap<Integer, String>(); hmap.put(12, "Eleni"); hmap.put(2, "Thomas"); hmap.put(7, "Bob"); hmap.put(49, "Rahul"); hmap.put(3, "Alice "); // Display content using Iterator Set set = hmap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry mentry = (Map.Entry) iterator.next(); System.out.print("key is: " + mentry.getKey() + " & Value is: "); System.out.println(mentry.getValue()); }

slide-44
SLIDE 44

HashMap Example

import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.Set; public class HashMapExample { public static void main(String args[]) { HashMap<Integer, String> hmap = new HashMap<Integer, String>(); hmap.put(12, "Eleni"); hmap.put(2, "Thomas"); hmap.put(7, "Bob"); hmap.put(49, "Rahul"); hmap.put(3, "Alice "); // Display content using Iterator Set set = hmap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry mentry = (Map.Entry) iterator.next(); System.out.print("key is: " + mentry.getKey() + " & Value is: "); System.out.println(mentry.getValue()); }

slide-45
SLIDE 45

HashMap Example

import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.Set; public class HashMapExample { public static void main(String args[]) { HashMap<Integer, String> hmap = new HashMap<Integer, String>(); hmap.put(12, "Eleni"); hmap.put(2, "Thomas"); hmap.put(7, "Bob"); hmap.put(49, "Rahul"); hmap.put(3, "Alice "); // Display content using Iterator Set set = hmap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry mentry = (Map.Entry) iterator.next(); System.out.print("key is: " + mentry.getKey() + " & Value is: "); System.out.println(mentry.getValue()); }

Returns a Set view of the mappings contained in this map.

slide-46
SLIDE 46

HashMap Example

import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.Set; public class HashMapExample { public static void main(String args[]) { HashMap<Integer, String> hmap = new HashMap<Integer, String>(); hmap.put(12, "Eleni"); hmap.put(2, "Thomas"); hmap.put(7, "Bob"); hmap.put(49, "Rahul"); hmap.put(3, "Alice "); // Display content using Iterator Set set = hmap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry mentry = (Map.Entry) iterator.next(); System.out.print("key is: " + mentry.getKey() + " & Value is: "); System.out.println(mentry.getValue()); }

A key/value pair that forms one element of a Map.

slide-47
SLIDE 47

HashMap Example

import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.Set; public class HashMapExample { public static void main(String args[]) { HashMap<Integer, String> hmap = new HashMap<Integer, String>(); hmap.put(12, "Eleni"); hmap.put(2, "Thomas"); hmap.put(7, "Bob"); hmap.put(49, "Rahul"); hmap.put(3, "Alice "); // Display content using Iterator Set set = hmap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry mentry = (Map.Entry) iterator.next(); System.out.print("key is: " + mentry.getKey() + " & Value is: "); System.out.println(mentry.getValue()); }

Returns the key corresponding to this entry.

slide-48
SLIDE 48

HashMap Example

// Get values based on key String var = hmap.get(2); System.out.println("Value at index 2 is: " + var); // Remove values based on key hmap.remove(3); System.out.println("Map key and values after removal:"); Set set2 = hmap.entrySet(); Iterator iterator2 = set2.iterator(); while (iterator2.hasNext()) { Map.Entry mentry2 = (Map.Entry) iterator2.next(); System.out.print("Key is: " + mentry2.getKey() + " & Value is: "); System.out.println(mentry2.getValue()); } } }

slide-49
SLIDE 49

HashMap Example

// Get values based on key String var = hmap.get(2); System.out.println("Value at index 2 is: " + var); // Remove values based on key hmap.remove(3); System.out.println("Map key and values after removal:"); Set set2 = hmap.entrySet(); Iterator iterator2 = set2.iterator(); while (iterator2.hasNext()) { Map.Entry mentry2 = (Map.Entry) iterator2.next(); System.out.print("Key is: " + mentry2.getKey() + " & Value is: "); System.out.println(mentry2.getValue()); } } }

slide-50
SLIDE 50

HashMap Example

// Get values based on key String var = hmap.get(2); System.out.println("Value at index 2 is: " + var); // Remove values based on key hmap.remove(3); System.out.println("Map key and values after removal:"); Set set2 = hmap.entrySet(); Iterator iterator2 = set2.iterator(); while (iterator2.hasNext()) { Map.Entry mentry2 = (Map.Entry) iterator2.next(); System.out.print("Key is: " + mentry2.getKey() + " & Value is: "); System.out.println(mentry2.getValue()); } } }

slide-51
SLIDE 51

HashMap Example

key is: 49 & Value is: Rahul key is: 2 & Value is: Thomas key is: 3 & Value is: Alice key is: 7 & Value is: Bob key is: 12 & Value is: Eleni Value at index 2 is: Thomas Map key and values after removal: Key is: 49 & Value is: Rahul Key is: 2 & Value is: Thomas Key is: 7 & Value is: Bob Key is: 12 & Value is: Eleni

Output:

slide-52
SLIDE 52

HashMap Methods

  • void clear(): It removes all the key and value pairs from the specified Map.
  • Object clone(): It returns a copy of all the mappings of a map & is used for cloning them into another

map.

  • boolean containsKey(Object key): It is a boolean function which returns true or false based on

whether the specified key is found in the map.

  • boolean containsValue(Object Value): Similar to containsKey() method, however it looks for the

specified value instead of key.

  • Value get(Object key): It returns the value for the specified key.
  • boolean isEmpty(): It checks whether the map is empty. If there are no key-value mapping present in

the map then this function returns true else false.

  • Set keySet(): It returns the Set of the keys fetched from the map.
  • value put(Key k, Value v): Inserts key value mapping into the map. Used in the above example.
  • int size(): Returns the size of the map – Number of key-value mappings.
  • For more methods & info: https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
slide-53
SLIDE 53

Class ArrayList<E>

  • Widely used because of the functionality and flexibility it offers.
  • Allows null elements.
  • Very good alternative of traditional java arrays.
  • Can dynamically grow and shrink as per the need.
slide-54
SLIDE 54

ArrayList Example

import java.util.*; public class ArrayListExample { public static void main(String args[]) { ArrayList<String> obj = new ArrayList<String>(); // This is how elements should be added to the array list

  • bj.add("Alex");
  • bj.add("Harry");
  • bj.add("Chad");
  • bj.add("Steve");
  • bj.add("Anne");

// Displaying array list elements System.out.println("Currently the array list has following elements: " + obj);

slide-55
SLIDE 55

ArrayList Example

import java.util.*; public class ArrayListExample { public static void main(String args[]) { ArrayList<String> obj = new ArrayList<String>(); // This is how elements should be added to the array list

  • bj.add("Alex");
  • bj.add("Harry");
  • bj.add("Chad");
  • bj.add("Steve");
  • bj.add("Anne");

// Displaying array list elements System.out.println("Currently the array list has following elements: " + obj);

slide-56
SLIDE 56

ArrayList Example

import java.util.*; public class ArrayListExample { public static void main(String args[]) { ArrayList<String> obj = new ArrayList<String>(); // This is how elements should be added to the array list

  • bj.add("Alex");
  • bj.add("Harry");
  • bj.add("Chad");
  • bj.add("Steve");
  • bj.add("Anne");

// Displaying array list elements System.out.println("Currently the array list has following elements: " + obj);

slide-57
SLIDE 57

ArrayList Example

import java.util.*; public class ArrayListExample { public static void main(String args[]) { ArrayList<String> obj = new ArrayList<String>(); // This is how elements should be added to the array list

  • bj.add("Alex");
  • bj.add("Harry");
  • bj.add("Chad");
  • bj.add("Steve");
  • bj.add("Anne");

// Displaying array list elements System.out.println("Currently the array list has following elements: " + obj);

slide-58
SLIDE 58

ArrayList Example

// Add element at the given index

  • bj.add(0, "Rahul");
  • bj.add(1, "Justin");

// Remove elements from array list

  • bj.remove("Chad");
  • bj.remove("Harry");

System.out.println("Current array list is:" + obj); // Remove element from the given index

  • bj.remove(1);

System.out.println("Current array list is:" + obj); } }

slide-59
SLIDE 59

ArrayList Example

// Add element at the given index

  • bj.add(0, "Rahul");
  • bj.add(1, "Justin");

// Remove elements from array list

  • bj.remove("Chad");
  • bj.remove("Harry");

System.out.println("Current array list is:" + obj); // Remove element from the given index

  • bj.remove(1);

System.out.println("Current array list is:" + obj); } }

slide-60
SLIDE 60

ArrayList Example

// Add element at the given index

  • bj.add(0, "Rahul");
  • bj.add(1, "Justin");

// Remove elements from array list

  • bj.remove("Chad");
  • bj.remove("Harry");

System.out.println("Current array list is:" + obj); // Remove element from the given index

  • bj.remove(1);

System.out.println("Current array list is:" + obj); } }

slide-61
SLIDE 61

ArrayList Example

// Add element at the given index

  • bj.add(0, "Rahul");
  • bj.add(1, "Justin");

// Remove elements from array list

  • bj.remove("Chad");
  • bj.remove("Harry");

System.out.println("Current array list is:" + obj); // Remove element from the given index

  • bj.remove(1);

System.out.println("Current array list is:" + obj); } }

slide-62
SLIDE 62

ArrayList Example

// Add element at the given index

  • bj.add(0, "Rahul");
  • bj.add(1, "Justin");

// Remove elements from array list

  • bj.remove("Chad");
  • bj.remove("Harry");

System.out.println("Current array list is:" + obj); // Remove element from the given index

  • bj.remove(1);

System.out.println("Current array list is:" + obj); } }

slide-63
SLIDE 63

ArrayList Example

Currently the array list has following elements: [Alex, Harry, Chad, Steve, Anne] Current array list is: [Rahul, Justin, Alex, Steve, Anne] Current array list is: [Rahul, Alex, Steve, Anne]

Output:

slide-64
SLIDE 64

ArrayList Methods

  • add( Object o): This method adds an object o to the arraylist.
  • add(int index, Object o): It adds the object o to the array list at the given index.
  • remove(Object o): Removes the object o from the ArrayList.
  • remove(int index): Removes element from a given index.
  • set(int index, Object o): Used for updating an element. It replaces the element present at

the specified index with the object o.

  • int indexOf(Object o): Gives the index of the object o. If the element is not found in the list

then this method returns the value -1.

  • Object get(int index): It returns the object of list which is present at the specified index.
  • boolean contains(Object o): It checks whether the given object o is present in the array list

if its there then it returns true else it returns false.

  • For more methods & info: http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
slide-65
SLIDE 65

Class TreeSet<E>

  • Similar to HashSet except that it sorts the elements in the ascending order.
  • Allows null elements.
  • Does not allow duplicates.
slide-66
SLIDE 66

TreeSet Example

import java.util.TreeSet; public class TreeSetExample { public static void main(String args[]) { // TreeSet of String Type TreeSet<String> tset = new TreeSet<String>(); // Adding elements to TreeSet<String> tset.add("ABC"); tset.add("String"); tset.add("Test"); tset.add("Pen"); tset.add("Ink"); tset.add("Jack");

slide-67
SLIDE 67

TreeSet Example

import java.util.TreeSet; public class TreeSetExample { public static void main(String args[]) { // TreeSet of String Type TreeSet<String> tset = new TreeSet<String>(); // Adding elements to TreeSet<String> tset.add("ABC"); tset.add("String"); tset.add("Test"); tset.add("Pen"); tset.add("Ink"); tset.add("Jack");

slide-68
SLIDE 68

TreeSet Example

import java.util.TreeSet; public class TreeSetExample { public static void main(String args[]) { // TreeSet of String Type TreeSet<String> tset = new TreeSet<String>(); // Adding elements to TreeSet<String> tset.add("ABC"); tset.add("String"); tset.add("Test"); tset.add("Pen"); tset.add("Ink"); tset.add("Jack");

slide-69
SLIDE 69

TreeSet Example

//Displaying TreeSet System.out.println(tset); // TreeSet of Integer Type TreeSet<Integer> tset2 = new TreeSet<Integer>(); // Adding elements to TreeSet<Integer> tset2.add(88); tset2.add(7); tset2.add(101); tset2.add(0); tset2.add(3); tset2.add(222); System.out.println(tset2); } }

slide-70
SLIDE 70

TreeSet Example

//Displaying TreeSet System.out.println(tset); // TreeSet of Integer Type TreeSet<Integer> tset2 = new TreeSet<Integer>(); // Adding elements to TreeSet<Integer> tset2.add(88); tset2.add(7); tset2.add(101); tset2.add(0); tset2.add(3); tset2.add(222); System.out.println(tset2); } }

slide-71
SLIDE 71

TreeSet Example

//Displaying TreeSet System.out.println(tset); // TreeSet of Integer Type TreeSet<Integer> tset2 = new TreeSet<Integer>(); // Adding elements to TreeSet<Integer> tset2.add(88); tset2.add(7); tset2.add(101); tset2.add(0); tset2.add(3); tset2.add(222); System.out.println(tset2); } }

slide-72
SLIDE 72

TreeSet Example

[ABC, Ink, Jack, Pen, String, Test] [0, 3, 7, 88, 101, 222]

Output:

slide-73
SLIDE 73

TreeSet Methods

  • add( Object o): Adds the specified element to this set if it is not already present.
  • ceiling(Object o): Returns the least element in this set greater than or equal to the given

element, or null if there is no such element.

  • clear(): Removes all of the elements from this set.
  • contains(Object o): Returns true if this set contains the specified element.
  • first(): Returns the first (lowest) element currently in this set.
  • floor(Object o): Returns the greatest element in this set less than or equal to the given

element, or null if there is no such element.

  • last(): Returns the last (highest) element currently in this set.
  • For more methods & info: https://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html
slide-74
SLIDE 74

Class LinkedHashSet<E>

  • Also an implementation of Set interface.
  • Similar to HashSet & TreeSet except:
  • HashSet doesn’t maintain any kind of order of its elements.
  • TreeSet sorts the elements in ascending order.
  • LinkedHashSet maintains the insertion order. Elements gets sorted in the same

sequence in which they have been added to the Set.

slide-75
SLIDE 75

LinkedHashSet Example

import java.util.LinkedHashSet; public class LinkedHashSetExample { public static void main(String args[]) { // LinkedHashSet of String Type LinkedHashSet<String> lhset = new LinkedHashSet<String>(); // Adding elements to the LinkedHashSet lhset.add("Z"); lhset.add("PQ"); lhset.add("N"); lhset.add("O"); lhset.add("KK"); lhset.add("FGH"); System.out.println(lhset);

slide-76
SLIDE 76

LinkedHashSet Example

import java.util.LinkedHashSet; public class LinkedHashSetExample { public static void main(String args[]) { // LinkedHashSet of String Type LinkedHashSet<String> lhset = new LinkedHashSet<String>(); // Adding elements to the LinkedHashSet lhset.add("Z"); lhset.add("PQ"); lhset.add("N"); lhset.add("O"); lhset.add("KK"); lhset.add("FGH"); System.out.println(lhset);

slide-77
SLIDE 77

LinkedHashSet Example

import java.util.LinkedHashSet; public class LinkedHashSetExample { public static void main(String args[]) { // LinkedHashSet of String Type LinkedHashSet<String> lhset = new LinkedHashSet<String>(); // Adding elements to the LinkedHashSet lhset.add("Z"); lhset.add("PQ"); lhset.add("N"); lhset.add("O"); lhset.add("KK"); lhset.add("FGH"); System.out.println(lhset);

slide-78
SLIDE 78

LinkedHashSet Example

// LinkedHashSet of Integer Type LinkedHashSet<Integer> lhset2 = new LinkedHashSet<Integer>(); // Adding elements lhset2.add(99); lhset2.add(7); lhset2.add(0); lhset2.add(67); lhset2.add(89); lhset2.add(66); System.out.println(lhset2); } }

slide-79
SLIDE 79

LinkedHashSet Example

// LinkedHashSet of Integer Type LinkedHashSet<Integer> lhset2 = new LinkedHashSet<Integer>(); // Adding elements lhset2.add(99); lhset2.add(7); lhset2.add(0); lhset2.add(67); lhset2.add(89); lhset2.add(66); System.out.println(lhset2); } }

slide-80
SLIDE 80

LinkedHashSet Example

[Z, PQ, N, O, KK, FGH] [99, 7, 0, 67, 89, 66]

Output:

slide-81
SLIDE 81

LinkedHashSet Methods

  • Inherited from HashSet class: add, clear, clone, contains, isEmpty, iterator,

remove, size

  • Inherited from Set interface: add, addAll, clear, contains, containsAll, equals,

hashCode, isEmpty, iterator, remove, removeAll, retainAll, size, toArray, toArray

  • Other methods: equals, hashCode, removeAll, addAll, containsAll, retainAll,

toArray, toArray, toString, …

  • For more info:

https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashSet.html

slide-82
SLIDE 82

Class LinkedList<E>

  • Also an implementation of List interface (like ArrayList).
  • Fast for adding and deleting elements.
  • Slow to access a specific element.
  • Implemented as a double linked list.
slide-83
SLIDE 83

LinkedList Example

import java.util.*; public class LinkedListExample { public static void main(String args[]) { // Linked List Declaration LinkedList<String> linkedlist = new LinkedList<String>(); //add(String Element) is used for adding // the elements to the linked list linkedlist.add("Item1"); linkedlist.add("Item5"); linkedlist.add("Item3"); linkedlist.add("Item6"); linkedlist.add("Item2"); // Display Linked List Content System.out.println("Linked List Content: " +linkedlist); // Add First and Last Element linkedlist.addFirst("First Item"); linkedlist.addLast("Last Item"); System.out.println("LinkedList Content after addition: " +linkedlist);

slide-84
SLIDE 84

LinkedList Example

import java.util.*; public class LinkedListExample { public static void main(String args[]) { // Linked List Declaration LinkedList<String> linkedlist = new LinkedList<String>(); //add(String Element) is used for adding // the elements to the linked list linkedlist.add("Item1"); linkedlist.add("Item5"); linkedlist.add("Item3"); linkedlist.add("Item6"); linkedlist.add("Item2"); // Display Linked List Content System.out.println("Linked List Content: " +linkedlist); // Add First and Last Element linkedlist.addFirst("First Item"); linkedlist.addLast("Last Item"); System.out.println("LinkedList Content after addition: " +linkedlist);

slide-85
SLIDE 85

LinkedList Example

import java.util.*; public class LinkedListExample { public static void main(String args[]) { // Linked List Declaration LinkedList<String> linkedlist = new LinkedList<String>(); //add(String Element) is used for adding // the elements to the linked list linkedlist.add("Item1"); linkedlist.add("Item5"); linkedlist.add("Item3"); linkedlist.add("Item6"); linkedlist.add("Item2"); // Display Linked List Content System.out.println("Linked List Content: " +linkedlist); // Add First and Last Element linkedlist.addFirst("First Item"); linkedlist.addLast("Last Item"); System.out.println("LinkedList Content after addition: " +linkedlist);

slide-86
SLIDE 86

LinkedList Example

import java.util.*; public class LinkedListExample { public static void main(String args[]) { // Linked List Declaration LinkedList<String> linkedlist = new LinkedList<String>(); //add(String Element) is used for adding // the elements to the linked list linkedlist.add("Item1"); linkedlist.add("Item5"); linkedlist.add("Item3"); linkedlist.add("Item6"); linkedlist.add("Item2"); // Display Linked List Content System.out.println("Linked List Content: " +linkedlist); // Add First and Last Element linkedlist.addFirst("First Item"); linkedlist.addLast("Last Item"); System.out.println("LinkedList Content after addition: " +linkedlist);

slide-87
SLIDE 87

LinkedList Example

import java.util.*; public class LinkedListExample { public static void main(String args[]) { // Linked List Declaration LinkedList<String> linkedlist = new LinkedList<String>(); //add(String Element) is used for adding // the elements to the linked list linkedlist.add("Item1"); linkedlist.add("Item5"); linkedlist.add("Item3"); linkedlist.add("Item6"); linkedlist.add("Item2"); // Display Linked List Content System.out.println("Linked List Content: " +linkedlist); // Add First and Last Element linkedlist.addFirst("First Item"); linkedlist.addLast("Last Item"); System.out.println("LinkedList Content after addition: " +linkedlist);

slide-88
SLIDE 88

LinkedList Example

// This is how to get and set Values Object firstvar = linkedlist.get(0); System.out.println("First element: " +firstvar); linkedlist.set(0, "Changed first item"); Object firstvar2 = linkedlist.get(0); System.out.println("First element after update by set method: " +firstvar2); // Remove first and last element linkedlist.removeFirst(); linkedlist.removeLast(); System.out.println("LinkedList after deletion of first and last element: " +linkedlist); // Add to a Position and remove from a position linkedlist.add(0, "Newly added item"); linkedlist.remove(2); System.out.println("Final Content: " +linkedlist); } }

slide-89
SLIDE 89

LinkedList Example

// This is how to get and set Values Object firstvar = linkedlist.get(0); System.out.println("First element: " +firstvar); linkedlist.set(0, "Changed first item"); Object firstvar2 = linkedlist.get(0); System.out.println("First element after update by set method: " +firstvar2); // Remove first and last element linkedlist.removeFirst(); linkedlist.removeLast(); System.out.println("LinkedList after deletion of first and last element: " +linkedlist); // Add to a Position and remove from a position linkedlist.add(0, "Newly added item"); linkedlist.remove(2); System.out.println("Final Content: " +linkedlist); } }

slide-90
SLIDE 90

LinkedList Example

// This is how to get and set Values Object firstvar = linkedlist.get(0); System.out.println("First element: " +firstvar); linkedlist.set(0, "Changed first item"); Object firstvar2 = linkedlist.get(0); System.out.println("First element after update by set method: " +firstvar2); // Remove first and last element linkedlist.removeFirst(); linkedlist.removeLast(); System.out.println("LinkedList after deletion of first and last element: " +linkedlist); // Add to a Position and remove from a position linkedlist.add(0, "Newly added item"); linkedlist.remove(2); System.out.println("Final Content: " +linkedlist); } }

slide-91
SLIDE 91

LinkedList Example

Linked List Content: [Item1, Item5, Item3, Item6, Item2] LinkedList Content after addition: [First Item, Item1, Item5, Item3, Item6, Item2, Last Item] First element: First Item First element after update by set method: Changed first item LinkedList after deletion of first and last element: [Item1, Item5, Item3, Item6, Item2] Final Content: [Newly added item, Item1, Item3, Item6, Item2]

Output:

slide-92
SLIDE 92

LinkedList Methods

  • boolean add(Object item): It adds the item at the end of the list.
  • void add(int index, Object item): It adds an item at the given index of the the list.
  • boolean addAll(Collection c): It adds all the elements of the specified collection c to the list.
  • boolean addAll(int index, Collection c): It adds all the elements of collection c to the list

starting from a give index in the list.

  • void addFirst(Object item): It adds the item (or element) at the first position in the list.
  • void addLast(Object item): It inserts the specified item at the end of the list.
  • void clear(): It removes all the elements of a list.
  • Object clone(): It returns the copy of the list.
  • For more methods & info: https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html
slide-93
SLIDE 93

Summary

  • Java Collections framework
  • Main Collection Interface
  • Main General Purpose Implementations: HashSet, HashMap, ArrayList,

TreeSet, LinkedHashSet, LinkedList

  • Next: Linked Lists