tshepang
tshepang

Reputation: 12459

How to join elements of HashSet into a String with a delimiter

I can do the following:

fn main() {
    let vec = vec!["first", "last"];
    println!("{}", vec.join(", "));
}

It gives this output:

first, last

If I try to use join with a map type, it fails:

error[E0599]: no method named join found for type std::collections::HashSet<&str> in the current scope

Upvotes: 9

Views: 5117

Answers (2)

Shepmaster
Shepmaster

Reputation: 431689

More efficiently, you can use itertools to join an iterator without collecting it into a Vec first:

extern crate itertools;

use std::collections::HashSet;
use itertools::Itertools;

fn main() {
    let hash_set: HashSet<_> = ["first", "last"].iter().collect();

    // Either of
    println!("{}", hash_set.iter().join(", "));
    println!("{}", itertools::join(&hash_set, ", "));
}

Upvotes: 9

ljedrz
ljedrz

Reputation: 22273

You can convert a HashSet into an Iterator, collect it and then use .join():

use std::collections::HashSet;

fn main() {
    let mut books = HashSet::new();

    books.insert("A Dance With Dragons");
    books.insert("To Kill a Mockingbird");
    books.insert("The Odyssey");
    books.insert("The Great Gatsby");

    println!("{}", books.into_iter().collect::<Vec<&str>>().join(", "));
}

You could do the same with a HashMap - you would just need to extract its .keys() or .values() first, depending on which you want to join.

Upvotes: 9

Related Questions