Sling Academy
Home/Rust/Transforming a LinkedList<T> into other Rust collections

Transforming a LinkedList into other Rust collections

Last updated: January 04, 2025

In Rust, the LinkedList<T> is a collection type that provides a doubly linked list structure for organizing data. Although typically not as performant as the Vec<T>, it still holds valuable use cases where insertions and deletions are frequent. However, you might encounter situations where transforming a LinkedList into other collection types, such as Vec, HashSet, or HashMap, becomes necessary. This article will guide you through the process of efficiently transforming a LinkedList into various Rust collections using practical code examples.

Transforming LinkedList<T> into Vec<T>

The Vec<T> is a dynamic array type that is highly flexible and enables rapid random access. You can easily transform a LinkedList<T> into a Vec<T> required for scenarios needing index-based operations.

use std::collections::LinkedList;

fn main() {
    let mut linked_list: LinkedList<isize> = LinkedList::new();
    linked_list.push_back(10);
    linked_list.push_back(20);
    linked_list.push_back(30);

    // Transforming LinkedList into Vec
    let vector: Vec<isize> = linked_list.iter().cloned().collect();

    // Printing the Vec
    println!("{:?}", vector); // Output: [10, 20, 30]
}

The iter().cloned().collect() pattern is utilized, first iterating over the LinkedList elements, then cloning (copying by value) each element, and finally collecting them into a Vec<T>.

Transforming LinkedList<T> into HashSet<T>

To remove duplicates and achieve a collection with unique elements, a HashSet<T> is often suitable. The transformation process can be accomplished similarly using the collect method.

use std::collections::{LinkedList, HashSet};

fn main() {
    let mut linked_list: LinkedList<isize> = LinkedList::new();
    linked_list.push_back(10);
    linked_list.push_back(20);
    linked_list.push_back(10); // duplicate

    // Transform to HashSet to remove duplicates
    let hash_set: HashSet<isize> = linked_list.into_iter().collect();

    // Printing the HashSet
    println!("{:?}", hash_set); // Output might be: {10, 20}
}

Note here that we used into_iter. This makes the LinkedList<T> ownership move into an iterator, removing the need to clone the elements.

Transforming LinkedList<T> into HashMap<K, V>

For numeric pairings, constructing a HashMap<K, V> where each two elements from the LinkedList serve as a key-value pair is achievable using Rust's iterator functionalities.

use std::collections::{LinkedList, HashMap};

fn main() {
    let mut linked_list: LinkedList<(isize, &'static str)> = LinkedList::new();
    linked_list.push_back((1, "One"));
    linked_list.push_back((2, "Two"));
    linked_list.push_back((3, "Three"));

    // Transform to HashMap
    let hash_map: HashMap<isize, &str> = linked_list.into_iter().collect();

    // Printing the HashMap
    println!("{:?}", hash_map); // Output: {1: "One", 2: "Two", 3: "Three"}
}

In this code, elements in the LinkedList are already tuples representing key-value pairs. Collecting such an `iterable` directly results in a HashMap.

Conclusion

By leveraging Rust's standard library, transforming LinkedList<T> into other collections like Vec<T>, HashSet<T>, and HashMap<K, V> is straightforward. This process generally relies on Rust's collect method, facilitating clean and efficient code. Understanding these conversion techniques expands flexibility in data manipulations and enhances the use of collections tailored to specific requirements.

Next Article: Rust - Implementing custom algorithms on LinkedList: merges, splits, and more

Previous Article: Why LinkedList is rarely used in Rust: performance and use cases

Series: Collections in Rust

Rust

You May Also Like

  • E0557 in Rust: Feature Has Been Removed or Is Unavailable in the Stable Channel
  • Network Protocol Handling Concurrency in Rust with async/await
  • Using the anyhow and thiserror Crates for Better Rust Error Tests
  • Rust - Investigating partial moves when pattern matching on vector or HashMap elements
  • Rust - Handling nested or hierarchical HashMaps for complex data relationships
  • Rust - Combining multiple HashMaps by merging keys and values
  • Composing Functionality in Rust Through Multiple Trait Bounds
  • E0437 in Rust: Unexpected `#` in macro invocation or attribute
  • Integrating I/O and Networking in Rust’s Async Concurrency
  • E0178 in Rust: Conflicting implementations of the same trait for a type
  • Utilizing a Reactor Pattern in Rust for Event-Driven Architectures
  • Parallelizing CPU-Intensive Work with Rust’s rayon Crate
  • Managing WebSocket Connections in Rust for Real-Time Apps
  • Downloading Files in Rust via HTTP for CLI Tools
  • Mocking Network Calls in Rust Tests with the surf or reqwest Crates
  • Rust - Designing advanced concurrency abstractions using generic channels or locks
  • Managing code expansion in debug builds with heavy usage of generics in Rust
  • Implementing parse-from-string logic for generic numeric types in Rust
  • Rust.- Refining trait bounds at implementation time for more specialized behavior