Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to consume a HashMap and get a vector of values in Rust?

Tags:

hashmap

rust

I have a hashmap: HashMap<SomeKey, SomeValue> and I want to consume the hashmap and get all its values as a vector.

The way I do it right now is

let v: Vec<SomeValue> = hashmap.values().cloned().collect();

cloned copies each value, but this construction doesn't consume the hashmap. I am OK with consuming the map.

Is there some way to get values without copying them?

like image 735
Ishamael Avatar asked Jan 17 '20 20:01

Ishamael


People also ask

How to extract keys and values from a hashmap in rust?

In Rust, we can extract the keys and values from a HashMap using the iter() and keys() / get() / unwrap() functions. Note that iter() return all key-value pairs in arbitrary order.

How to place the keys and values of a hashmap into vector?

We can place the keys, values, or both keys and values at once into a vector. Version 1 We use from_iter and pass the result of iter () called on the HashMap. This is a vector containing both keys and values. Version 2 Here we just get a vector of str references from the keys () of the HashMap. This is probably a common usage of from_iter.

What is HashMap in Java?

The concept of HashMap is present in almost all programming languages like Java, C++, Python, it has key-value pairs and through key, we can get values of the map. Keys are unique no duplicates allowed in the key but the value can be duplicated.

How to display the content of an array without loops in rust?

For example, in Rust, we can display the content of an Array, Tuple, HashMap (Map), or Vector without loops using the Debug trait. These three compound types, by default, implement the Debug trait.


1 Answers

Convert the entire HashMap into an iterator and discard the keys:

use std::collections::HashMap;

fn only_values<K, V>(map: HashMap<K, V>) -> impl Iterator<Item = V> {
    map.into_iter().map(|(_k, v)| v)
}

You can then do whatever you want with the iterator, including collecting it into a Vec<_>.

See also:

  • How do I collect the values of a HashMap into a vector?
like image 128
Shepmaster Avatar answered Sep 20 '22 12:09

Shepmaster