Ch 16: Data Structures - Set and Map

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Copyright © 2013 by John Wiley & Sons. All rights reserved. THE JAVA COLLECTIONS FRAMEWORK CHAPTER Slides by Donald W. Smith TechNeTrain.com 15.
CSci 143 Sets & Maps Adapted from Marty Stepp, University of Washington
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
Sets and Maps Chapter 9. Chapter 9: Sets and Maps2 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn about.
Java Collection Framework. Interface Collection add(o) Add a new element clear() Remove all elements contains(o) Membership checking. IsEmpty() Whether.
Chapter 16.  Data structures that take control of organizing elements  Elements not in fixed positions  Advantage – better performance Adding Removing.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Chapter 19 Java Data Structures
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 15 – The Java Collections Framework.
Collections. Why collections? Collections are used to hold a collection of objects. List holds objects based on order of insertion and can hold non unique.
ADSA: Maps/ Advanced Data Structures and Algorithms Objectives – –examples of maps, and introduce map collection views Semester 2,
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 15 – The Java Collections Framework.
The Java Collections Framework (Part 2) By the end of this lecture you should be able to: Use the HashMap class to store objects in a map; Create objects.
Big Java Chapter 16.
111 © 2002, Cisco Systems, Inc. All rights reserved.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Building Java Programs Chapter 11 Lecture 11-1: Sets and Maps reading:
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 15 – The Java Collections Framework.
תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.
Sets, Maps and Hash Tables. RHS – SOC 2 Sets We have learned that different data struc- tures have different advantages – and drawbacks Choosing the proper.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
CHAPTER 20 Advanced Data Structures. CHAPTER GOALS To learn about set and map data types To understand the implementation of hash tables To be able to.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
SETS AND MAPS Collections of Data. Advanced Data Structures Often referred to as the Java Collections Framework…. Set and map data types Hash tables Binary.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 16 – Advanced Data Structures.
1/79 13 주 컬렉션 (Collection) 제네릭스 (Generics) 자바프로그래밍강원대학교.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
1 Maps, Stacks and Queues Maps Reading:  2 nd Ed: 20.4, 21.2, 21.7  3 rd Ed: 15.4, 16.2, 16.7 Additional references: Online Java Tutorial at
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
CSE 143 Lecture 11: Sets and Maps reading:
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Sets and Maps Chapter 9.
Slides by Donald W. Smith
Using the Java Collection Libraries COMP 103 # T2
Building Java Programs
Slides by Donald W. Smith
Slides by Donald W. Smith
CSC 321: Data Structures Fall 2016 Balanced and other trees
Unit 1 Hadoop and big data
Chapter 19 Java Data Structures
Wednesday Notecards. Wednesday Notecards Wednesday Notecards.
Software Development Java Collections
Chapter 15 –The Java Collections Framework
Data Structures TreeMap HashMap.
Efficiency add remove find unsorted array O(1) O(n) sorted array
Road Map CS Concepts Data Structures Java Language Java Collections
Week 6 Discussion Word Cloud.
TreeSet TreeMap HashMap
TCSS 342, Winter 2006 Lecture Notes
CSE 373: Data Structures and Algorithms
Maps Grammars Based on slides by Marty Stepp & Alyssa Harding
Sets, Maps and Hash Tables
Recitation Outline C++ STL associative containers Examples
Exercise Write a program that counts the number of unique words in a large text file (say, Moby Dick or the King James Bible). Store the words in a collection.
CS2110: Software Development Methods
CSE 373 Java Collection Framework, Part 2: Priority Queue, Map
Containers and Iterators
Sets and Maps Chapter 9.
slides created by Alyssa Harding
slides created by Marty Stepp
slides created by Marty Stepp
CSC 321: Data Structures Fall 2018 Balanced and other trees
Presentation transcript:

Ch 16: Data Structures - Set and Map Yonglei Tao

A set is a collection of elements Sets A set is a collection of elements Every element is unique Ordering is irrelevant Elements can be added, located, and removed Adding a duplicate of an existing element is silently ignored No way to visit elements in the order in which they are added

Set Implementation in Standard Java Library Class HashSet Uses a hash table as its data structure It arranges its elements so they can be located quickly Class TreeSet Uses a balanced binary tree as its data structure It keeps its elements in a way that makes it easy to fetch in ascending order Implementation with Linked lists - relatively slow to add, remove, and locate elements As a rule of thumb, use a hash set unless you want to visit the set elements in sorted order

Add and remove elements: Using a Set Construct the Set: Set<String> names = new HashSet<String>(); or Set<String> names = new TreeSet<String>(); Add and remove elements: names.add("Romeo"); names.remove("Juliet"); Test whether an element is contained in the set: if (names.contains("Juliet")) . . .

Visiting All Elements with an Iterator Using the “for each” loop for (String name : names){ // do something with name here } Or using an iterator Iterator<String> iter = names.iterator(); while (iter.hasNext()){ String name = iter.next(); // do something with name here } A set iterator does not visit the elements in the order in which they were added An element cannot be added to a set at an iterator position A set element can be removed at an iterator position

Sample Program - SpellCheck public class SpellCheck { public static void main(String[] args) { // Read the dictionary and the document try { Set<String> dictionaryWords = readWords(“dictionary.txt"); Set<String> documentWords = readWords(“report.txt"); } catch (IOException e) { System.out.println(“Invalid input”); }   // Print all words that are in the document but not the dictionary for (String word : documentWords) { if (!dictionaryWords.contains(word)) System.out.println(word);

Sample Program – SpellCheck (Cont.) /** Reads all words from a file. @param filename the name of the file @return a set with all lowercased words in the file. Here, a word is a sequence of upper- and lowercase letters. */ public static Set<String> readWords(String filename) { Set<String> words = new HashSet<String>(); Scanner in = new Scanner(new File(filename)); // Use any characters other than a-z or A-Z as delimiters in.useDelimiter("[^a-zA-Z]+"); while (in.hasNext()) { words.add(in.next().toLowerCase()); } return words; If you changed the code to use a TreeSet instead of a HashSet. How would the output change? Answer: The words would be listed in sorted order

Sample Program – SpellCheck (Cont.) Program Run: neighbouring croqueted pennyworth dutchess comfits xii dinn clamour ... When would you choose a tree set over a hash set? Answer: When it is desirable to visit the set elements in sorted order.

Maps A map is a set of key / value pairs It is a function from one set, the key set, to another set, the value set Every key in a map has a unique value, but a value may be associated with several keys Used to find the value that is associated with a key

Map Classes and Interfaces Class HashMap Uses a hash table to minimize the search time Class TreeMap Needs extra time to insert and retrieve keys Can produce keys in sorted order To find all keys and values in a map, iterate through the key set and find the values that correspond to the keys

Example: Associate names with colors Construct the Map: Using a Map Example: Associate names with colors Construct the Map: Map<String, Color> favoriteColors = new HashMap<String, Color>(); or new TreeMap<String, Color>(); Add an association: favoriteColors.put("Juliet", Color.RED); Change an existing association: favoriteColors.put("Juliet",Color.BLUE);

Get the value associated with a key: Using a Map Get the value associated with a key: Color julietsFavoriteColor = favoriteColors.get("Juliet”); Remove a key and its associated value: favoriteColors.remove("Juliet"); Find if this map contains a mapping for a key: favoriteColors.containsKey(“Jackson"); Print key/value pairs Set<String> keySet = m.keySet(); for (String key : keySet) { Color value = m.get(key); System.out.println(key + ” : " + value); }

MapDemo.java public class MapDemo { public static void main(String[] args) { Map<String, Color> favoriteColors = new HashMap<String, Color>(); favoriteColors.put("Juliet", Color.BLUE); favoriteColors.put("Romeo", Color.GREEN); favoriteColors.put("Adam", Color.RED); favoriteColors.put("Eve", Color.BLUE); // Print all keys and values in the map Set<String> keySet = favoriteColors.keySet(); for (String key : keySet) { Color value = favoriteColors.get(key); System.out.println(key + " : " + value); }

MapDemo.java (cont.) Program Run: Romeo : java.awt.Color[r=0,g=255,b=0] Eve : java.awt.Color[r=0,g=0,b=255] Adam : java.awt.Color[r=255,g=0,b=0] Juliet : java.awt.Color[r=0,g=0,b=255] What is the difference between a set and a map? Answer: A set stores elements. A map stores associations between keys and values. Why is the collection of the keys of a map a set? Answer: The ordering does not matter, and you cannot have duplicates.