Java Map and Set collections



Similar documents
CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

Introduction to Programming System Design. CSCI 455x (4 Units)

The Java Collections Framework

Data Structures in the Java API

cs2010: algorithms and data structures

Data Structures and Algorithms Lists

dictionary find definition word definition book index find relevant pages term list of page numbers

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Class 32: The Java Collections Framework

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

JAVA COLLECTIONS FRAMEWORK

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Analysis of a Search Algorithm

LINKED DATA STRUCTURES

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

Generic Types in Java. Example. Another Example. Type Casting. An Aside: Autoboxing 4/16/2013 GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK.

Big O and Limits Abstract Data Types Data Structure Grand Tour.

CompSci-61B, Data Structures Final Exam

Computer Programming I

Basic Programming and PC Skills: Basic Programming and PC Skills:

6. Standard Algorithms

Sequential Data Structures

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

Searching Algorithms

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Working with Java Collections

Node-Based Structures Linked Lists: Implementation

Sequences in the C++ STL

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Introduction to Data Structures

Linked Lists: Implementation Sequences in the C++ STL

Data Structures and Algorithms Written Examination

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

ADTs,, Arrays, Linked Lists

Efficient Data Structures for Decision Diagrams

: provid.ir

Chapter 8: Bags and Sets

Binary Search Trees CMPSC 122

D06 PROGRAMMING with JAVA

The ADT Binary Search Tree

Lecture 2: Data Structures Steven Skiena. skiena

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Review of Hashing: Integer Keys

Practical Session 4 Java Collections

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Binary Search Trees. basic implementations randomized BSTs deletion in BSTs

Ordered Lists and Binary Trees

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

C h a p t e r. C h a p t e r G o a l s

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Algorithms and Data Structures Written Exam Proposed SOLUTION

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

LSP 121. LSP 121 Math and Tech Literacy II. Simple Databases. Today s Topics. Database Class Schedule. Simple Databases

STACKS,QUEUES, AND LINKED LISTS

Symbol Tables. Introduction

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

Algorithms and Data S tructures Structures Stack, Queues, and Applications Applications Ulf Leser

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

CMSC 202H. ArrayList, Multidimensional Arrays

Zabin Visram Room CS115 CS126 Searching. Binary Search

Pseudo code Tutorial and Exercises Teacher s Version

recursion, O(n), linked lists 6/14

Lecture 9. Semantic Analysis Scoping and Symbol Table

AP Computer Science Java Mr. Clausen Program 9A, 9B

Java Coding Practices for Improved Application Performance

PHP Arrays for RPG Programmers

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

7.1 Our Current Model

Loops and ArrayLists

Binary Trees and Huffman Encoding Binary Search Trees

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Lab Experience 17. Programming Language Translation

PES Institute of Technology-BSC QUESTION BANK

DATA STRUCTURE - STACK

Binary Search Trees. Data in each node. Larger than the data in its left child Smaller than the data in its right child

Stacks. Data Structures and Data Types. Collections

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

1 of 1 24/05/ :23 AM

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

Software Engineering Techniques

Sources: On the Web: Slides will be available on:

Data Structures and Algorithms

10CS35: Data Structures Using C

Transcription:

Java Map and Set collections Java Set container idea interface Java Map container idea interface iterator concordance example Java maps and sets [Bono] 1

Announcements Lab this week based on an example we ll do in Thurs lecture Xuanni s Tues office hours moved to Wed 1 4pm (Sal 125) this week only. Sample MT 2 exams have been published. Reminders: PA 3 due this Wed MT 2 Tue. 4/5 in THH 101 (same loc. as MT1) Java maps and sets [Bono] 2

Java Collections Collection is an interface in Java Linear collections: ArrayList, LinkedList, Stack, Queue ordering of elements depended on order and type of insertion Two others today: Set and Map ordering is determined internally by the class based on value of the element Java maps and sets [Bono] 3

Set ADT (ADT = abstract data type) Operations: add an element (no duplicate elements added) remove an element ask if an object is in the set list all the elements (order of visiting depends on the kind of set created) Java maps and sets [Bono] 4

Set Examples Determine the number of unique words in a text file. (P16.1 from text) Spell-checker (Ex from Section 16.1 of text) Java maps and sets [Bono] 5

Java Set interface Two implementations: Set<ElmtType> s = new HashSet<ElmtType>(); fastest. for when you don't care about order when iterating, or if you don t need to iterate. ElmtType must support equals() and hashcode() Set<ElmtType> s = new TreeSet<ElmtType>(); for when you need to visit element in sorted order. ElmtType must implement Comparable (has compareto) Normally use interface type for object reference. E.g., Set<String> uniquewords = new TreeSet<String>(); Java maps and sets [Bono] 6

Java Set interface (cont.) Set<String> uniquewords = new TreeSet<String>(); creates empty set uniquewords.add("the"); if wasn't there, adds it and returns true, o.w., returns false and set unchanged uniquewords.remove("blob"); if it was there, removes it and returns true, o.w., returns false and set unchanged uniquewords.contains("the") returns true iff "the" is in the set size() isempty() Java maps and sets [Bono] 7

Iterating over a Set Iterator is also an interface. Order elements visited depends on kind of Set involved. Can iterate over other Collections like we did with LinkedList. E.g., Iterator<String> iter = uniquewords.iterator(); while (iter.hasnext()) { String word = iter.next(); } System.out.println(word); // or do something else with it Java maps and sets [Bono] 8

more about ElmtType best if it's an immutable type (e.g., String, Integer) Do not "mutate" element contents while in the Set: Set<Point> setofpoints =... Iterator<Point> iter = setofpoints.iterator(); while (iter.hasnext()) { } Point p = iter.next(); p.translate(x, y); // DON T DO THIS // invalidates setofpoints Java maps and sets [Bono] 9

How many unique words in a file? public static int numunique(scanner in) { Java maps and sets [Bono] 10

Map ADT A map stores a collection of (key,value) pairs keys are unique: a pair can be identified by its key Operations: add a new (key, value) pair (called an entry) remove an entry, given its key lookup an entry, given its key list all the entries (order of visiting depends on the kind of map created) Java maps and sets [Bono] 11

Key set Example: map of students and their Joe scores Value set Mary Sam Sally 50 100 87 Kate Java maps and sets [Bono] 12

Java Map interface Creation is same as Set, but two type parameters for generic class. Map<KeyType, ValueType> map = new HashMap<KeyType,ValueType>(); fastest. for when you don't care about order when iterating, or if you don t need to iterate. KeyType must support equals() and hashcode() Map<KeyType, ValueType> map = new TreeMap<KeyType,ValueType>(); for when you need to visit element in sorted order by keys. KeyType must implement Comparable (has compareto) Java maps and sets [Bono] 13

Java Map interface (cont.) Create an empty map: Map<String, Integer> scores = new TreeMap<String, Integer>(); Note: put operation can be used in two ways: Suppose we do the two operations in sequence: scores.put("joe", 98); // inserts if key wasn't there, adds it and returns null, o.w., returns the old value that went with this key scores.put("joe", 100); // updates changes Joe's score to 100. if "Joe" hadn't been there before, this would have added him. Java maps and sets [Bono] 14

Java Map interface (cont.) Map<String, Integer> scores = new TreeMap<String, Integer>(); scores.remove("joe"); if key was there, removes it and returns the value that went with this key, o.w., returns null and map is unchanged Integer jscore = scores.get("joe"); return the value that goes with "Joe", or null if "Joe" is not in the map Java maps and sets [Bono] 15

Iterating over a Map A little different than Set or LinkedList. Suppose Map<String, Integer> scores Can iterate over all keys or all entries First get the "view" of the Map you need: scores.keyset() returns the set of keys (type Set<String>) scores.entryset() returns a set whose elements are map entries (more details soon) Second, iterate over the set that was returned. Java maps and sets [Bono] 16

Iterating over all keys in a map Map<String, Integer> scores = new TreeMap<String, Integer>();... Set<String> keyset = scores.keyset(); Iterator<String> iter = keyset.iterator(); while (iter.hasnext())... Version without temp variable keyset: Iterator<String> iter = scores.keyset().iterator(); Java maps and sets [Bono] 17

Iterating over all entries in a Map Using example map: Map<String, Integer> scores; Reminder: scores.entryset() returns a set of map entries. Elements of this set are type: Map.Entry<String, Integer> Operations on a Map.Entry<K,V> entry: entry.getkey() entry.getvalue() entry.setvalue(newval) Java maps and sets [Bono] 18

Iterating over all entries in a Map (cont.) Example with Map<String, Integer> scores Map<String, Integer> scores = new TreeMap<String, Integer>();... Set<Map.Entry<String, Integer>> setview = scores.entryset(); Iterator<Map.Entry<String, Integer>> iter = setview.iterator(); while (iter.hasnext()) { } Map.Entry<String, Integer> curr = iter.next(); System.out.println(curr.getKey() + " + curr.getvalue()); Java maps and sets [Bono] 19

for-each loop For some traversals we can use a for-each loop as a shortcut. General form (uses for keyword): for (ElmtType elmt: collection) { } do something with element Example with visiting all entries in a Map: for (Map.Entry<String, Integer> entry: scores.entryset()) { System.out.println(entry.getKey() + + entry.getvalue()); } Java maps and sets [Bono] 20

Final notes on Map interface Restrictions on KeyType in a Map (Same issue as with ElmtType of Set) best if it's an immutable type (e.g., String, Integer) Unsafe to "mutate" keys that are in a Map. Entry s location in Map data structure depends on its key. No iterator on Maps directly: have to use keyset() or entryset() and iterate over resulting Set. Java maps and sets [Bono] 21

Map seen as an array Map ADT is sometimes called an associative array System.out.println(scores.get( Joe )); ArrayList index syntax, but it s not random access But it s fast: TreeMap: get, put, remove O(log n) each. HashMap: get, put, remove O(1) each (!) E.g., Need an array indexed by a String?... use a Map Java maps and sets [Bono] 22

Example: concordance Problem: find the number of occurrences of each word in a text document. Why? (Variation also finds the page numbers or line numbers where those words occur in the document.) Java maps and sets [Bono] 23

Example: concordance (cont.) Similar to finding frequencies of student scores (from earlier in the semester): // sample scores: 72 99 84 99 72 85 72 80 // scores are all in range [0..100] int[] freq = new int[101]; for each score freq[score]++; Can we use an array in the same way for this problem?: Find the number of occurrences of each word in a text document. Java maps and sets [Bono] 24