This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
Idiom #113 Iterate over map entries, ordered by values
Print each key k with its value x from an associative array mymap, in ascending order of x.
Multiple entries may exist for the same value x.
- C++
- C#
- D
- Dart
- Elixir
- Go
- Go
- Haskell
- Haskell
- JS
- Java
- Java
- Java
- Perl
- Perl
- Prolog
- Python
- Python
- Python
- Python
- Ruby
- Rust
- Rust
for_each(begin(mymap), end(mymap),
[&s](const auto& kv) { s.insert(kv.second); });
Using a std::multiset<>
mymap
|> Map.to_list
|> Enum.sort(fn ({_k1, val1}, {_k2, val2}) -> val1 <= val2 end)
|> Enum.each(fn ({k, v}) -> IO.puts("#{k}: #{v}") end)
We need to convert our map to a list to sort it. When converted, the list is a set of two element tuples which we can sort based on the last value. Finally we just want to iterate over those sorted tuples.
type entry struct {
key string
value int
}
entries := make([]entry, 0, len(mymap))
for k, x := range mymap {
entries = append(entries, entry{key: k, value: x})
}
sort.Slice(entries, func(i, j int) bool {
return entries[i].value < entries[j].value
})
for _, e := range entries {
fmt.Println("Key =", e.key, ", Value =", e.value)
}
Using sort.Slice incurs slightly less boilerplate than sort.Sort.
type entry struct {
key string
value int
}
type entries []entry
func (list entries) Len() int { return len(list) }
func (list entries) Less(i, j int) bool { return list[i].value < list[j].value }
func (list entries) Swap(i, j int) { list[i], list[j] = list[j], list[i] }
entries := make(entries, 0, len(mymap))
for k, x := range mymap {
entries = append(entries, entry{key: k, values: x})
}
sort.Sort(entries)
for _, e := range entries {
fmt.Println("Key =", e.key, ", Value =", e.value)
}
Define custom types entry and entries.
Then create a flat list of entries, and sort it.
Then create a flat list of entries, and sort it.
mapM_ print . sortOn snd $ Map.toList mymap
Using Map.toList to convert the map to a list of (key, value) pairs, then sort the list based on the second element of the pair with sortOn snd.
mapM_ print $ sortBy (comparing snd) $ Map.toList mymap
Map.toList gives a list of all (key,value) pairs. Sorts on the values (second item of the pairs) and prints.
$ is apply operator and serves here only to save parentheses.
$ is apply operator and serves here only to save parentheses.
mymap.entrySet()
.stream()
.sorted(comparingByValue())
.forEach(out::println);
The `Map.Entry` object will print "k=x".
mymap.entrySet()
.stream()
.sorted(comparingByValue())
.forEach(e -> {
K k = e.getKey();
X x = e.getValue();
});
sub by_val_then_key {
return ($mymap{$a} <=> $mymap{$b})
or ($a cmp $b)
}
for my $k (sort by_val_then_key keys %mymap) {
print "$k: $mymap{$k}\n";
}
Create a custom, reusable sort routine and use it by name.
Assuming the keys are strings, we use <=> to compare the numeric values, and cmp to use the lexical order of the key as a tie breaker.
Assuming the keys are strings, we use <=> to compare the numeric values, and cmp to use the lexical order of the key as a tie breaker.
dict_pairs(D, _, Ps),
transpose_pairs(Ps, TPs),
keysort(TPs, Val_sorted),
forall(member(V-K, Val_sorted),
format("~w:~w~n", [V, K]))
Transpose the key-value pair list, sort by key (a stable sort), then print
programming-idioms.org