0% found this document useful (0 votes)
72 views19 pages

Dr. Avinash Gautam CSIS, BITS Pilani: Java Collection Framework: Maps and Sets

This document provides an overview of Maps and Sets in the Java Collection Framework. It discusses how Maps provide a mapping between keys and values, with HashMap being the preferred implementation. Sets are unordered collections that do not allow duplicates. HashSet is covered as the main Set implementation. Typical set operations like union, intersection and difference are also summarized.

Uploaded by

saisounya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views19 pages

Dr. Avinash Gautam CSIS, BITS Pilani: Java Collection Framework: Maps and Sets

This document provides an overview of Maps and Sets in the Java Collection Framework. It discusses how Maps provide a mapping between keys and values, with HashMap being the preferred implementation. Sets are unordered collections that do not allow duplicates. HashSet is covered as the main Set implementation. Typical set operations like union, intersection and difference are also summarized.

Uploaded by

saisounya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Java Collection Framework: Maps and Sets

Dr. Avinash Gautam


CSIS, BITS Pilani

1
Lists, revisited
 Lists are slow for searching
 indexOf, contains are slow (O(n))
 must potentially look at each element of list

public int indexOf(Object o) {


for (int i = 0; i < size(); i++)
if (get(i).equals(o))
return i;
return -1;
}
2
A new collection type: Set
 set: an unordered collection with no duplicates
 main purpose of a set is to test objects for membership
 operations are exactly those for Collection

 interface java.util.Set has the following methods:

boolean containsAll(Collection c);


boolean addAll(Collection c);
int size(); boolean removeAll(Collection c);
boolean isEmpty(); boolean retainAll(Collection c);
boolean contains(Object e); void clear();
boolean add(Object e);
boolean remove(Object e); Object[] toArray();
Iterator iterator(); Object[] toArray(Object[] a);

3
Set implementations in Java
 Set is an interface; you can't say new Set()
 There are two implementations:
 java.util.HashSet is best for most purposes
 we won't use the other one: TreeSet
 Java's set implementations have been optimized so
that it is very fast to search for elements in them
 contains method runs in constant time!

 Preferred:Set s = new HashSet();


Not: HashSet s = new HashSet();
4
Iterators for Sets
 A set has a method iterator to create an
iterator over the elements in the set

 The iterator has the usual methods:


 boolean hasNext()
 Object next()
 void remove()

5
Typical set operations
 Sometimes it is useful to compare sets:
 subset: S1 is a subset of S2 if S2 contains every element
from S1.

 Many times it is useful to combine sets in the following


ways:
 union: S1 union S2 contains all elements that are in S1 or
S2.
 intersection: S1 intersect S2 contains only the elements
that are in both S1 and S2.
 difference: S1 difference S2 contains the elements that are
in S1 that are not in S2.

 How could we implement these operations using the


methods in Java's Set interface?
6
How does a HashSet work?
 every object has a reasonably-unique
associated number called a hash code
 public int hashCode() in class Object
 HashSet stores its elements in an array a
such that a given element o is stored at
index o.hashCode() % array.length
 any element in the set must be placed in one
exact index of the array
 searching for this element later, we just have
to check that one place to see if it's there
(O(1))
 "Tom Katz".hashCode() % 10 == 6
 "Sarah Jones".hashCode() % 10 == 8
 "Tony Balognie".hashCode() % 10 == 9
 you don't need to understand this...
7
Membership testing in HashSets
 When testing whether a HashSet contains a given
object:
 Java computes the hashCode for the given object
 looks in that index of the HashSet's internal array
 Java compares the given object with the object in the HashSet's
array using equals; if they are equal, returns true
 Hence, an object will be considered to be in the set
only if both:
 It has the same hash code as an element in the set, and
 The equals comparison returns true
 An object that is put into a HashSet works best if it
has a public int hashCode()method defined
 String, Integer, Double, etc. have this already
8
Mapping between sets
 sometimes we want to create a mapping
between elements of one set and another set
 example: map people to their phone numbers
 "Marty Stepp" -->"253-692-4540"
 "Jenny" -->"253-867-5309"

 How would we do this with a list (or list(s))?


 A list doesn't map people to phone numbers; it
maps ints from 0 .. size - 1 to objects
 Could we map some int to a person's name, and
the same int to the person's phone number?
 How would we find a phone number, given the
person's name? Is this a good solution?
9
A new collection: Map
 map: an unordered collection that associates a
collection of element values with a set of keys so that
elements they can be found very quickly (O(1))
 Each key can appear at most once (no duplicate keys)
 A key maps to at most one value
 the main operations:
 put(key, value)
"Map this key to that value."
 get(key)
"What value, if any, does this key map to?"
 maps are also called:
 hashes or hash tables
 dictionaries
 associative arrays
10
Java's Map interface
public interface Map {
Object put(Object key, Object value);
Object get(Object key);
Object remove(Object key);
Basic ops boolean containsKey(Object key);
boolean containsValue(Object value);
int size();
boolean isEmpty();

void putAll(Map map);


Bulk ops void clear();

Collection Set keySet();


views Collection values();
}

11
Map implementations in Java
 Map is an interface; you can't say new Map()
 There are two implementations:
 java.util.HashMap is best for most purposes
 we won't use the other one: TreeMap

 Preferred:Map m = new HashMap();


Not: HashMap m = new HashMap();

12
HashMap example
HashMap grades
HashMap grades = new HashMap();
grades.put("Martin", "A");
grades.put("Nelson", "F"); HashMapEntry
grades.put("Milhouse", "B");

// What grade did they get?


System.out.println( "Martin" "A"
HashMap
grades.get("Nelson"));
System.out.println( 0 HashMapEntry
grades.get("Martin"));

grades.put("Nelson", "W");
2 "Nelson" "F"
grades.remove("Martin");
HashMapEntry
System.out.println(
grades.get("Nelson"));
System.out.println(
grades.get("Martin")); 5 "Milhouse" "B"

13
Map example
public class Birthday {
public static void main(String[] args){
Map m = new HashMap();
m.put("Newton", new Integer(1642));
m.put("Darwin", new Integer(1809));
System.out.println(m);
}
}

Output:
{Darwin=1809, Newton=1642}

14
Some Map methods in detail

public Object get(Object key)

returns the value at the specified key, or null if the key is
not in the map


public boolean containsKey(Object key)

returns true if the map contains a mapping for the
specified key


public boolean containsValue(Object val)

returns true if the map contains the specified object as a
value

15
Collection views
 A map itself is not regarded as a collection
 Map does not implement Collection interface
 although, in theory, it could be seen as a collection
of pairs

16
Iterators and Maps
 Map interface has no iterator method; you can’t get an Iterator
directly

 must first call either


 keySet() returns a Set of all the keys in this Map
 values() returns a Collection of all the values in this Map

 then call iterator() on the key set or values


 Examples:
Iterator keyItr = grades.keySet().iterator();
Iterator elementItr = grades.values().iterator();
 If you really want the keys or element values in a more familiar
collection such as an ArrayList, use the ArrayList constructor that
takes a Collection as its argument
ArrayList elements = new ArrayList(grades.values());
17
Examining all elements

Usually iterate by getting the set of keys, and iterating
over that

Set keys = m.keySet();


Iterator itr = keys.iterator();
while (itr.hasNext()) {
Object key = itr.next();
System.out.println(key + "=>" +
m.get(key));
}

Output:
Darwin => 1809
Newton => 1642
18
References
 The Java Tutorial: Collections.
http://java.sun.com/docs/books/tutorial/
collections/index.html

19

You might also like