如何以功能方式从列表创建地图? [英] How do I create a map from a list in a functional way?

查看:45
本文介绍了如何以功能方式从列表创建地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中,有一个名为 toMap 的方法可以处理任何元组列表并将其转换为映射,其中键是元组的第一项,值是第二项:

In Scala, there is a method named toMap that works on any list of tuples and converts it to a map where the key is the first item on the tuple and the value is the second one:

val listOfTuples = List(("one", 1), ("two", 2))
val map = listOfTuples.toMap 

什么是 Rust 中最接近 toMap 的东西?

What is the closest thing to toMap in Rust?

推荐答案

使用 Iterator::collect:

use std::collections::HashMap;

fn main() {
    let tuples = vec![("one", 1), ("two", 2), ("three", 3)];
    let m: HashMap<_, _> = tuples.into_iter().collect();
    println!("{:?}", m);
}

collect 利用 FromIterator 特性.任何迭代器都可以收集到实现 FromIterator 的类型中.在这种情况下,HashMap 将其实现为:

collect leverages the FromIterator trait. Any iterator can be collected into a type that implements FromIterator. In this case, HashMap implements it as:

impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
where
    K: Eq + Hash,
    S: HashState + Default,

换句话说,任何元组迭代器的第一个值可以是hashed比较完全相等 可以转换到 HashMap.S 参数并不令人兴奋,它只是定义了哈希方法是什么.

Said another way, any iterator of tuples where the first value can be hashed and compared for total equality can be converted to a HashMap. The S parameter isn't exciting to talk about, it just defines what the hashing method is.

另见:

我应该做哪些更改才能获得存储在 Vec 中的具有相同键的所有值?

what change should I make so that I get all the values with same key stored in a Vec?

标准库中没有用于此的单行/函数式方法.相反,使用 entry API:

There's no one-line / functional method for this in the standard library. Instead, use the entry API:

use std::collections::HashMap;

fn main() {
    let tuples = vec![("one", 1), ("two", 2), ("one", 3)];
    let mut m = HashMap::new();
    for (k, v) in tuples {
        m.entry(k).or_insert_with(Vec::new).push(v)
    }
    println!("{:?}", m);
}

如果您发现自己经常这样做,您可以创建自己的类型并为其实现FromIterator:

If you found yourself doing this frequently, you could create your own type and implement FromIterator for it:

use std::{cmp::Eq, collections::HashMap, hash::Hash, iter::FromIterator};

struct MyCoolType<K: Eq + Hash, V>(HashMap<K, Vec<V>>);

impl<K: Eq + Hash, V> FromIterator<(K, V)> for MyCoolType<K, V> {
    fn from_iter<I>(tuples: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
    {
        let mut m = HashMap::new();
        for (k, v) in tuples {
            m.entry(k).or_insert_with(Vec::new).push(v)
        }
        Self(m)
    }
}

fn main() {
    let tuples = vec![("one", 1), ("two", 2), ("one", 3)];
    let MyCoolType(m) = tuples.into_iter().collect();
    println!("{:?}", m);
}

另见:

这篇关于如何以功能方式从列表创建地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆