I'm able to parse my input into effectively an Iterator<Iterator<i32>>
where each inner iterator is length 2. The input looks like:
0: 3
1: 2
2: 4
4: 8
6: 5
8: 6
...
I can parse this with:
input.lines()
.map(|line| line.split(": ")
.filter_map(|n| n.parse::<i32>().ok()))
The best way I came up with to put this into a HashMap
is:
let mut tmp_map: HashMap<i32, i32> = HashMap::new();
for mut pair in input.lines()
.map(|line| line.split(": ")
.filter_map(|n| n.parse::<i32>().ok()))
{
tmp_map.insert(pair.next().unwrap(), pair.next().unwrap());
}
...which seems very unwieldy. Is there a way to collect this iterator into a HashMap
?
HashMap
implementsFromIterator<(K, V)>
. Then it's just a matter of converting the text into an iterator of tuples. I like usingItertools::tuples
:See also: