Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

End-to-end testing is a very useful method to make sure that your application works as intended. This highlights issues in the overall functionality of the software, that the unit and integration test stages may miss.

Playwright is an easy-to-use, but powerful tool that automates end-to-end testing, and supports all modern browsers and platforms.

When coupled with LambdaTest (an AI-powered cloud-based test execution platform) it can be further scaled to run the Playwright scripts in parallel across 3000+ browser and device combinations:

>> Automated End-to-End Testing With Playwright

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

1. Introduction

LinkedList is a doubly-linked list implementation of the List and Deque interfaces. It implements all optional list operations and permits all elements (including null).

2. Features

Below you can find the most important properties of the LinkedList:

  • Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index
  • It is not synchronized
  • Its Iterator and ListIterator iterators are fail-fast (which means that after the iterator’s creation, if the list is modified, a ConcurrentModificationException will be thrown)
  • Every element is a node, which keeps a reference to the next and previous ones
  • It maintains insertion order

Although LinkedList is not synchronized, we can retrieve a synchronized version of it by calling the Collections.synchronizedList method, like:

List list = Collections.synchronizedList(new LinkedList(...));

3. Comparison to ArrayList

Although both of them implement the List interface, they have different semantics – which will definitely affect the decision of which one to use.

3.1. Structure

An ArrayList is an index-based data structure backed by an Array. It provides random access to its elements with a performance equal to O(1).

On the other hand, a LinkedList stores its data as a list of elements, and every element is linked to its previous and next element. In this case, the search operation for an item has execution time equal to O(n).

3.2. Operations

The insertion, addition and removal operations of an item are faster in a LinkedList because there is no need to resize an array or update the index when an element is added to some arbitrary position inside the collection, only references in surrounding elements will change.

3.3. Memory Usage

A LinkedList consumes more memory than an ArrayList because of every node in a LinkedList stores two references, one for its previous element and one for its next element, whereas ArrayList holds only data and its index.

4. Different Methods to Initialize a LinkedList

We can initialize a LinkedList using one of two constructors. Further, we use constructors to initialize new instances of a class.

4.1. Initializing an Empty LinkedList

We use the empty LinkedList() constructor to initialize an empty LinkedList.

Let’s demonstrate an example of a LinkedList parameterized over String using generics.

Let’s use a JUnit 5 test to verify the empty LinkedList:

@Test
public void whenInitializingLinkedList_ShouldReturnEmptyList() throws Exception {
    LinkedList<String> linkedList=new LinkedList<String>();     
    Assertions.assertTrue(linkedList.isEmpty());
}

Accordingly, we can add String elements to this list:

linkedList.addFirst("one");
linkedList.add("two");
linkedList.add("three");

Likewise, we can initialize a LinkedList of any class type.

4.2. Initializing a LinkedList From a Collection

We can also use the LinkedList(Collection<? extends E> c) constructor when we want to initialize a LinkedList whose elements are the elements of a given Collection. It adds the elements in the order in which the Collection‘s iterator returns them.

Let’s demonstrate an example of a LinkedList parameterized over  Integer using generics. However, first, we create a Collection to use as the argument when we invoke the constructor. Let’s create a Collection of type ArrayList parameterized over Integer using generics:

ArrayList<Integer> arrayList = new ArrayList<Integer>(3);

 arrayList.add(Integer.valueOf(1));
 arrayList.add(Integer.valueOf(2));
 arrayList.add(Integer.valueOf(3));

Afterward, let’s call the constructor to initialize a LinkedList:

LinkedList<Integer> linkedList=new LinkedList<Integer>(arrayList);

Again, let’s use a JUnit 5 test to verify the LinkedList derives its elements from the ArrayList it is constructed from:

@Test
public void whenInitializingListFromCollection_ShouldReturnCollectionsElements() throws Exception {
    ArrayList<Integer> arrayList=new ArrayList<Integer>(3);
        
    arrayList.add(Integer.valueOf(1));
    arrayList.add(Integer.valueOf(2));
    arrayList.add(Integer.valueOf(3));
 
    LinkedList<Integer> linkedList=new LinkedList<Integer>(arrayList);

    Object[] linkedListElements = linkedList.toArray();
    Object[] collectionElements = arrayList.toArray();

    Assertions.assertArrayEquals(linkedListElements,collectionElements);
}

Similarly, we can initialize LinkedList using any Java Collection. Accordingly, the elements of the LinkedList initialized from a Collection are the type of the Collection‘s elements.

5. Usage

Here are some code samples that show how you can use LinkedList:

5.1. Creation

LinkedList<Object> linkedList = new LinkedList<>();

5.2. Adding Element

LinkedList implements List and Deque interface, besides standard add() and addAll() methods you can find addFirst() and addLast(), which adds an element in the beginning or the end, respectively.

5.3. Removing Element

Similar to element addition, this list implementation offers removeFirst() and removeLast().

Also, there are convenient methods, such as removeFirstOccurence() and removeLastOccurence(), which return a boolean (true if the collection contained the specified element).

5.4. Queue Operations

Deque interface provides queue-like behaviors (actually, Deque extends Queue interface):

linkedList.poll();
linkedList.pop();

Those methods retrieve the first element and remove it from the list.

The difference between poll() and pop() is that pop will throw NoSuchElementException() on empty list, whereas poll returns null. The APIs pollFirst() and pollLast() are also available.

Here’s, for example, how the push API works:

linkedList.push(Object o);

Which inserts the element as the head of the collection.

LinkedList has many other methods, most of which should be familiar to a user who already used Lists. Others that are provided by Deque might be a convenient alternative to “standard” methods.

The full documentation can be found here.

6. Insert an Element at a Specific Position in a LinkedList

When we want to add an element at a specific position in a LinkedList, we have several method options:

Method Description
addFirst(E e) Adds an element at the beginning of a list
addLast(E e) Adds an element at the end of a list
add(E e) Adds an element at the end of a list
add(int index, E element) Adds an element at index position i of a list

Let’s demonstrate using each of these methods. Further, let’s initialize an empty list:

LinkedList<String> linkedList=new LinkedList<String>();

Afterward, let’s add the first element using the method addFirst(E e):

linkedList.addFirst("one");

Although we can build the list by repeatedly calling the add(E e) method, we want to demonstrate the different options for adding an element at a specific position. Therefore, let’s add the last element in the list using the method addLast(E e):

linkedList.addLast("three");

Let’s call the add(E e) method to add an element to the end of the list built so far:

linkedList.add("four");

A LinkedList uses a 0-based index, which means that the first element is at index 0, the second element at index 1, the third element at index 2, and so on. To create a sequence, let’s add the element “two” at index position 1 using add(int index, E element):

linkedList.add(1,"two");

Let’s use a JUnit 5 test to verify we added the elements in the LinkedList at specific, respective positions:

@Test
public void whenAddingElementsInLinkedListAtSpecificPosition_ShouldReturnElementsInProperSequence() throws Exception {
    LinkedList<String> linkedList=new LinkedList<String>();
        
    linkedList.addFirst("one");
    linkedList.addLast("three");
    linkedList.add("four");
    linkedList.add(1,"two");

    Object[] linkedListElements = linkedList.toArray();
    Object[] expectedListElements = {"one","two","three","four"};

    Assertions.assertArrayEquals(linkedListElements,expectedListElements);
}

The JUnit test should pass, verifying that we added elements at specific positions in a LinkedList.

7. Converting an Array into a LinkedList

In some cases, we may have data in the form of an array, and we need to work with it as a LinkedList for efficient insertions or to take advantage of the Deque operations that LinkedList provides. Converting an array to a LinkedList is straightforward in Java.

First, let’s start with a sample array of elements:

String[] array = { "apple", "banana", "cherry", "date" };

We can convert this array into a LinkedList by passing it to the Arrays.asList() method and then creating a new LinkedList from the resulting List:

List<String> list = Arrays.asList(array);  // Convert array to List
LinkedList<String> linkedList = new LinkedList<>(list);

Now linkedList contains all the elements from the original array, and we can use any of the LinkedList operations on it.

Another approach to convert an array into a LinkedList is by using the Collections.addAll() method. This method provides a simple way to add all elements from an array directly into a LinkedList.

First, we create an empty LinkedList. Then we use the Collections.addAll() method to add each element from the array into the LinkedList:

LinkedList<String> linkedList = new LinkedList<>();
Collections.addAll(linkedList, array);

After this operation, linkedList contains all the elements from the array and it preserves the order.

8. Conclusion

ArrayList is usually the default List implementation.

However, there are certain use cases where using LinkedList will be a better fit, such as preferences for constant insertion/deletion time (e.g., frequent insertions/deletions/updates), over constant access time and effective memory usage.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (All)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)