1

First, about joining the keys unordered. I found a few similar topics (like this one, which is for &str keys though) and the simplest solution I could come up with was this:

let s = my_hash_map.keys().map(|n| n.to_string()).collect::<Vec<_>>().join(",");

Is there a simpler way to do it?

Also, I would often prefer the elements in the resulting string to be sorted, but from what I've seen the standard library still doesn't provide a sorted() method I could simply plug into the above chain (as we normally would in Python, for example). So is there some other standard (with no external crates) simple way we could do that in a one-liner in Rust?

at54321
  • 8,726
  • 26
  • 46
  • 1
    Well, the straightforward solution is to collect into a vec, sort it and use code to join them. I don't say why you one a one liner. – Stargateur Oct 01 '21 at 18:28
  • This may not be an option for you, but `BTreeMap` is sorted. – Herohtar Oct 01 '21 at 18:44
  • If you really want, there is [`.sorted()`](https://docs.rs/itertools/0.10.1/itertools/trait.Itertools.html#method.sorted) provided by the `itertools` crate. Why do you not like external crates? Though keep in mind it simply collects into a vec, sorts it, and yields that as an iterator. – kmdreko Oct 01 '21 at 18:52
  • Why do you need a one liner ? – Svetlin Zarev Oct 01 '21 at 21:09
  • Thanks for your comments, guys. I know that `BTreeMap`'s keys are sorted, and I sometimes I use it, but other times there is a good reason not to. I know about `itertools`, but I would like to know if some standard stuff exists for that. Why a "one-liner"? Because I believe brevity is good, unless it worsens readability, quality, etc. I'm definitely not saying one-liners are always good, of course. But for me, it's good to have that option. – at54321 Oct 02 '21 at 05:38

1 Answers1

0

Well, instead of a "oneliner" each time, just create a funtion and call that "oneliner" function each time:

fn join_sorted(strs: impl Iterator<Item = String>, separator: &str) -> String {
    let mut v: Vec<_> = strs.collect();
    v.sort();
    v.join(separator)
}

Playground

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • That doesn't quite answer my question. But since nobody came up with a standard shorter "one-liner" solution, I guess such simply doesn't exist. Nonetheless, thank you for the function - it could be helpful to readers. – at54321 Oct 02 '21 at 09:41
  • @at54321, yeah, there is no solution that do not involves a third party crate (which in the end does something like this). – Netwave Oct 02 '21 at 14:53