15 Set Map Iterator
15 Set Map Iterator
Lecture 15
Sets and Maps; Iterators
• This doesn't let us easily ask which TAs got a given GPA.
– How would we structure a map for that?
4
Reversing a map
• We can reverse the mapping to be from GPAs to names.
Map<Double, String> taGpa = new HashMap<Double, String>();
taGpa.put(3.6, "Jared");
taGpa.put(4.0, "Alyssa");
taGpa.put(2.9, "Steve");
taGpa.put(3.6, "Stef");
taGpa.put(2.9, "Rob");
...
System.out.println("Who got a 3.6? " +
taGpa.get(3.6)); // ???
– must be careful to initialize the set for a given GPA before adding
6
Exercises
• Modify the word count program to print every word that
appeared in the book at least 1000 times, in sorted order from
least to most occurrences.
"Marty" true
Set
false
"Marty" "206-685-2181"
Map
8
Iterators
index 0 1 2 3 4 5 6 7 8 9 "the"
list value 3 8 9 7 5 12 0 0 0 0 set "to" "we"
size 6 "from"
11
Iterator methods
hasNext() returns true if there are more elements to examine
next() returns the next element from the collection (throws a
NoSuchElementException if there are none left to examine)
remove() removes the last value returned by next() (throws an
IllegalStateException if you haven't called next() yet)
15
Iterators and linked lists
• Iterators are particularly useful with linked lists.
– The previous code is O(N2) because each call on get must start
from the beginning of the list and walk to index i.
– Using an iterator, the same code is O(N). The iterator remembers
its position and doesn't start over each time.
current element: -3
iterator
current index: 1
16
Exercise
• Modify the Book Search program from last lecture to eliminate
any words that are plural or all-uppercase from the collection.
17
ListIterator
add(value) inserts an element just after the iterator's position
hasPrevious() true if there are more elements before the iterator
nextIndex() the index of the element that would be returned the next
time next is called on the iterator
previousIndex() the index of the element that would be returned the next
time previous is called on the iterator
previous() returns the element before the iterator (throws a
NoSuchElementException if there are none)
set(value) replaces the element last returned by next or previous
with the given value
ListIterator<String> li = myList.listIterator();