Ordered Collections

append()

The .append(&mut other) method on BTreeMap<K, V> and BTreeSet<T> moves all elements out of other into self, leaving other empty and overwriting any duplicate keys in self with the values from other.

Signatures and Merge Algorithm

// On BTreeMap<K, V>:
pub fn append(&mut self, other: &mut Self)

// On BTreeSet<T>:
pub fn append(&mut self, other: &mut Self)

Because both self and other are already sorted in ascending Ord order, a.append(&mut b) merges the two sorted sequences in $O(n + m)$ linear time (and reuses other directly when self is empty) rather than performing $m \log(n + m)$ individual tree insertions:

map_a: { 10: "old_10", 20: "old_20" }
map_b: { 20: "new_20", 30: "new_30" }

map_a.append(&mut map_b):
  ├── map_a: { 10: "old_10", 20: "new_20", 30: "new_30" }  (key 20 overwritten by map_b!)
  └── map_b: {} (empty)

Merging Two BTreeMap and BTreeSet Instances

use std::collections::{BTreeMap, BTreeSet};

fn main() {
    let mut defaults = BTreeMap::from([
        ("host", "127.0.0.1"),
        ("port", "8080"),
        ("tls", "false"),
    ]);

    let mut overrides = BTreeMap::from([
        ("port", "8443"),
        ("tls", "true"),
        ("workers", "4"),
    ]);

    // Moves all entries from `overrides` into `defaults`; matching keys take `overrides`'s value:
    defaults.append(&mut overrides);

    println!("Merged config:   {defaults:?}");
    println!("Overrides empty: {}", overrides.is_empty());

    // Merging two BTreeSets:
    let mut set_a = BTreeSet::from([1, 2, 3]);
    let mut set_b = BTreeSet::from([3, 4, 5]);
    set_a.append(&mut set_b);
    println!("Merged set:      {set_a:?} (set_b len={})", set_b.len());
}
Merged config:   {"host": "127.0.0.1", "port": "8443", "tls": "true", "workers": "4"}
Overrides empty: true
Merged set:      {1, 2, 3, 4, 5} (set_b len=0)

append(&mut other) vs. extend(other)

Method Receiver Parameter Asymptotic Complexity Best Used When...
a.append(&mut b) &mut BTreeMap<K, V> $O(|a| + |b|)$ sorted merge Both inputs are already BTreeMap / BTreeSet instances of similar size
a.extend(iter) Any IntoIterator<Item = (K, V)> $O(|b| \log(|a| + |b|))$ Inserting a small number of elements into a huge existing BTreeMap, or extending from a non-BTree iterator