SoFunction
Updated on 2025-03-04

Detailed explanation of several methods of Java collection in order of addition

In Java, if you need to followAdd orderStorage and operation elements are available in the following data structures. These structures provide different functional characteristics while preserving the order of element insertion.

1. Use ArrayList

Features

  • OrderfulArrayListElements will be stored in the order of addition.
  • Repeat allowed: Repeated elements can be stored.
  • Random access: Supports fast index-by-index access operation, time complexity isO(1)
  • Threads are not safe: By default, non-thread-safe and requires manual synchronization.

Example

import ;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        ("Apple");
        ("Banana");
        ("Cherry");

        ("ArrayList: " + list); // Output: [Apple, Banana, Cherry]    }
}

2. Use LinkedList

Features

  • OrderfulLinkedListStore elements in the order of insertion.
  • Repeat allowed: Supports duplicate elements.
  • Efficient insertion and deletion: The complexity of insertion and deletion operation time at the head or tail isO(1), but the random access performance is poor (time complexityO(n))。
  • Two-way linked list implementation: Support queue, stack and other functions.

Example

import ;

public class LinkedListExample {
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        ("Apple");
        ("Banana");
        ("Cherry");

        ("LinkedList: " + list); // Output: [Apple, Banana, Cherry]    }
}

3. Use LinkedHashSet

Features

  • OrderfulLinkedHashSetIt will be stored in the order of insertion of elements.
  • Go to the heavy: Duplicate elements are not allowed to be stored.
  • Underlying implementation:based onHashMapand bidirectional linked list.
  • Applicable scenarios: The insertion order needs to be preserved and deduplication needs to be deduplicated.

Example

import ;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        LinkedHashSet<String> set = new LinkedHashSet<>();
        ("Apple");
        ("Banana");
        ("Cherry");
        ("Apple"); // Repeat elements will be ignored
        ("LinkedHashSet: " + set); // Output: [Apple, Banana, Cherry]    }
}

4. Use LinkedHashMap

Features

  • OrderfulLinkedHashMapStore key-value pairs in the order of insertion.
  • Allow duplicate values: The key cannot be repeated, but the value can be repeated.
  • Quick access: Supports quick access to values ​​through keys (time complexity isO(1))。
  • Underlying implementation:based onHashMapand bidirectional linked list.
  • Applicable scenarios: The insertion order of key-value pairs needs to be preserved.

Example

import ;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
        (1, "Apple");
        (2, "Banana");
        (3, "Cherry");

        ("LinkedHashMap: " + map); // Output: {1=Apple, 2=Banana, 3=Cherry}    }
}

5. Use Stream to collect as an ordered collection

If the data source is disordered, e.g.HashSetOr raw arrays, Java's Stream API provides a way to convert data into ordered collections in order of insertion.

Example: Collected as List

import ;
import ;
import ;

public class StreamOrderedExample {
    public static void main(String[] args) {
        List<String> list = ("Cherry", "Apple", "Banana");

        List<String> orderedList = ()
                                       .collect(()); // Keep the original order
        ("Ordered List: " + orderedList); // Output: [Cherry, Apple, Banana]    }
}

Example: Collected as LinkedHashSet

import ;
import ;
import ;
import ;

public class StreamToOrderedSet {
    public static void main(String[] args) {
        List<String> list = ("Apple", "Banana", "Cherry", "Apple");

        Set<String> orderedSet = ()
                                     .collect((LinkedHashSet::new));

        ("Ordered Set: " + orderedSet); // Output: [Apple, Banana, Cherry]    }
}

6. Performance comparison of various data structures

Data structure Insert order Repeat allowed Time complexity: Insert Time complexity: Find Time complexity: Delete Remark
ArrayList Keep insertion order allow O(1) (tail) O(1) (by index) O(n) (intermediate element) Suitable for frequent access, but slower insertion and deletion
LinkedList Keep insertion order allow O(1) (head/tail) O(n) (Random access) O(1) (head/tail) High efficiency in insertion and deletion, suitable for queue scenarios
LinkedHashSet Keep insertion order Not allowed O(1) O(1) O(1) Suitable for scenes where order is required and deduplication is deduplicated
LinkedHashMap Keep insertion order The key cannot be repeated O(1) O(1) O(1) Suitable for scenarios where key-value pairs are stored in order
Stream Process in order of data sources Controllable Related to data sources Related to data sources Related to data sources Flexible, but mainly used for one-time operations

Summarize

In Java, the following collections can store data in the order of addition:

  • ArrayListandLinkedList: Suitable for scenarios where frequent addition and deletion are required and accessed in order.
  • LinkedHashSetandLinkedHashMap: Suitable for scenarios where sequential storage and deduplication or key-value pair operations are required.
  • Stream: Used for one-time operation, converting unordered data into an ordered set.

According to actual needs, select the appropriate data structure to meet performance and functional needs. For example, if you need to preserve the insertion order and deduplicate it, selectLinkedHashSet;If efficient random access is required, selectArrayList

This is the end of this article about several methods of Java collections in order of addition. For more information about Java collections in order of addition, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!