Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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

like image 509
tshepang Avatar asked Nov 30 '17 16:11

tshepang


2 Answers

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, ", "));
}
like image 165
Shepmaster Avatar answered Oct 13 '22 13:10

Shepmaster


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.

like image 20
ljedrz Avatar answered Oct 13 '22 13:10

ljedrz