Group by keys of several hashmaps

I have several hashmaps with String keys and i32 values.

Building on top of this solution, I'd like to flat map the hashmaps into key, value tuples so that I can group them by keys and then return a final grouping of (String, Vec) where each String contains the super set of i32 values from all of the hashmaps.

In functional style Rust it would look something like:

let groups = hashmaps.iter()
    .flat_map(|h| h.into_iter().collect::<Vec<(String, i32)>>()).collect::<Vec<(String, i32)>>()
    .group_by(|(k, v)| k)
    .into_iter()
    .map(|(k, group)| (k, group.cloned().unique().collect()))
    .collect::<Vec<(String, Vec<i32>)>>();

Unfortunately I hit this:

error[E0658]: use of unstable library feature 'slice_group_by'
--> app.rs:171:6
|
171 | .group_by(|(k, v)| k)
| ^^^^^^^^
|
= note: see issue #80552 https://github.com/rust-lang/rust/issues/80552 for more information

Is there a way forward I'm missing? Or a built-in support for this kind of operation rather than inventing my own wheel?

That solution is using the itertools crate's group_by method.

If you already have itertools as a dependency you need to import the extension trait to bring the method into scope
use itertools::Itertools;

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.