Java Get first item from a collection
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Java offers a variety of collection types under the Java Collections Framework lying within the java.util package. This framework includes sets, lists, queues, and other collections, all inheriting from the root interface Collection. Developers often face the need to retrieve the first element from these collections, but the method to achieve this effectively can vary depending on the specific type of collection used. This article examines standard procedures and nuances of accessing the first item across different Java collections, providing code examples and key considerations.
Retrieving the First Item from a List
Lists in Java (e.g., ArrayList, LinkedList) maintain elements in a sequential order, making them the most straightforward collections for accessing items by index. To get the first item of a list, one can use the get(int index) method with 0 as the index, if the list is not empty:
Retrieving the First Item from a Set
Sets like HashSet and LinkedHashSet do not maintain the order of elements, with LinkedHashSet being an exception as it maintains a predictable iteration order (the order in which elements were inserted). To retrieve the first item from a set, one must use an iterator:
Note that the "first" item in a HashSet is unpredictable due to the nature of hashing.
Retrieving the First Item from a Queue
Queues (LinkedList, PriorityQueue, etc.) are designed for holding elements prior to processing and typically offer methods like peek() or element() to look at the head of the queue without removing it:
Considerations and Best Practices
- Check for Empty Collections: Always verify if the collection is non-empty to avoid
NoSuchElementExceptionorIndexOutOfBoundsException. - Efficiency: Retrieving the first element from a LinkedList or an ArrayList is fast (O(1) time complexity). However, be aware of the internal implementation of different types of collections, as efficiency might vary.
- Modification Impact: Be aware that modification of the underlying collection (especially in concurrent scenarios) may affect iteration order, notably for sets.
Table of Methods for Different Collections
| Collection Type | Code Example | Method Used | Efficiency | Note |
| List | list.get(0); | get(int) | O(1) | Direct access by index |
| Set (HashSet) | iterator().next(); | Iterator | O(1) | Order is unpredictable |
| Set (LinkedHashSet) | iterator().next(); | Iterator | O(1) | Maintains insertion order |
| Queue | queue.peek(); | peek() | O(1) | Peeks without removing |
Advanced Uses and Edge Cases
In scenarios where collections might be accessed concurrently, consider thread-safe variants or handling synchronization appropriately. Also, in performance-sensitive applications, choosing the right type of collection based on access patterns (e.g., frequent retrievals, insertions) can dramatically impact the overall performance.
In summary, accessing the first element in Java collections depends highly on the type of collection used. The method of retrieval might differ based on whether order is preserved, and understanding the characteristics of each Java collection type is critical in choosing the best method for accessing elements efficiently.
Related reading
- Java Hashmap How to get key from value?
- Java HashMap.getObject infinite loop
- Java heap space - Out of memory error - Kafka Broker with SASL_SSL
- Java heap terminology young, old and permanent generations?
- Java Get last element after split
- Java Get month Integer from Date
- Java how can I split an ArrayList in multiple small ArrayLists?
- Java how to initialize String[]?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.