Skip to content

Commit 18f7b8f

Browse files
committed
Add methods for obtaining iterators over the keys and values of a TreeMap
1 parent a455345 commit 18f7b8f

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

src/libcollections/treemap.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,16 @@ impl<K: Ord, V> TreeMap<K, V> {
141141
/// Create an empty TreeMap
142142
pub fn new() -> TreeMap<K, V> { TreeMap{root: None, length: 0} }
143143

144+
/// Get a lazy iterator over the keys in the map.
145+
pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
146+
self.iter().map(|(k, _v)| k)
147+
}
148+
149+
/// Get a lazy iterator over the values in the map.
150+
pub fn values<'a>(&'a self) -> Values<'a, K, V> {
151+
self.iter().map(|(_k, v)| v)
152+
}
153+
144154
/// Get a lazy iterator over the key-value pairs in the map.
145155
/// Requires that it be frozen (immutable).
146156
pub fn iter<'a>(&'a self) -> Entries<'a, K, V> {
@@ -381,6 +391,15 @@ pub struct RevMutEntries<'a, K, V> {
381391
}
382392

383393

394+
/// TreeMap keys iterator
395+
pub type Keys<'a, K, V> =
396+
iter::Map<'static, (&'a K, &'a V), &'a K, Entries<'a, K, V>>;
397+
398+
/// TreeMap values iterator
399+
pub type Values<'a, K, V> =
400+
iter::Map<'static, (&'a K, &'a V), &'a V, Entries<'a, K, V>>;
401+
402+
384403
// FIXME #5846 we want to be able to choose between &x and &mut x
385404
// (with many different `x`) below, so we need to optionally pass mut
386405
// as a tt, but the only thing we can do with a `tt` is pass them to
@@ -1470,6 +1489,28 @@ mod test_treemap {
14701489
assert!(m_upper.iter().all(|(_, &x)| x == 0));
14711490
}
14721491

1492+
#[test]
1493+
fn test_keys() {
1494+
let vec = vec![(1i, 'a'), (2i, 'b'), (3i, 'c')];
1495+
let map = vec.move_iter().collect::<TreeMap<int, char>>();
1496+
let keys = map.keys().map(|&k| k).collect::<Vec<int>>();
1497+
assert_eq!(keys.len(), 3);
1498+
assert!(keys.contains(&1));
1499+
assert!(keys.contains(&2));
1500+
assert!(keys.contains(&3));
1501+
}
1502+
1503+
#[test]
1504+
fn test_values() {
1505+
let vec = vec![(1i, 'a'), (2i, 'b'), (3i, 'c')];
1506+
let map = vec.move_iter().collect::<TreeMap<int, char>>();
1507+
let values = map.values().map(|&v| v).collect::<Vec<char>>();
1508+
assert_eq!(values.len(), 3);
1509+
assert!(values.contains(&'a'));
1510+
assert!(values.contains(&'b'));
1511+
assert!(values.contains(&'c'));
1512+
}
1513+
14731514
#[test]
14741515
fn test_eq() {
14751516
let mut a = TreeMap::new();

0 commit comments

Comments
 (0)