Tutorial

How To Use Lists in Java

How To Use Lists in Java

Introduction

List is a built-in interface from the Java package java.util. Like arrays, lists allow you to group and store multiple elements in a collection. However, lists are more powerful and complex, providing advanced storage options and retrieving values.

One key difference with arrays is that you can store only objects in lists. Thus, you cannot store a primitive type directly in a list, but instead you have to use its wrapper class. Since a list is an interface in Java, it has different implementations. In this tutorial you will be using the ArrayList implementation class, also part of the built-in java.util package. ArrayList is commonly used because it is fast and lightweight. Still, the same code examples and principles should work if you choose another implementation.

Other implementations of the List interface are:

  • LinkedList is designed differently with a higher initialization cost regarding resources but more optimal for manipulating data.
  • Vector is synchronized, i.e., it is safe to be used in multi-threaded programs. However, synchronization comes with a performance cost on each operation for manipulating data, and that’s why it should be used only when needed.

Prerequisites

To follow this tutorial, you will need:

Creating lists

To create a list, you must declare it and initialize its implementation. In the following example, you will create a list using the ArrayList implementation and containing String objects. Open jshell and type:

Info: To follow the example code in this tutorial, open the Java Shell tool on your local system by running the jshell command. Then you can copy, paste, or edit the examples by adding them after the jshell> prompt and pressing ENTER. To exit jshell, type /exit.

  1. List<String> pets = new ArrayList<>();

The line above contains the following important parts:

  • List<String> means the object will be a list. The diamond <> operator is used to specify that the list object should be created with a String type argument. Specifying the type of arguments when creating a list is good practice. Otherwise, you risk trying to insert an object that cannot be cast, i.e., automatically converted, resulting in an error.
  • pets is the name of the list.
  • new ArrayList<>() means that you are creating a new object of type ArrayList. Here you can specify again that the list will hold String objects inside its diamond operator, but it’s not necessary because you have already specified it once in the beginning of the line.

The output from the jshell command above will be a confirmation that an empty pets lists has been created:

Output
pets ==> []

You might have noticed that when you created the pets list, you didn’t have to specify its size. The size of the list is dynamically taken care of by Java, and this gives you more flexibility when you don’t know beforehand the number of elements you will be storing in the list.

Adding List Elements

Once a list is created, you can start adding elements to it. You have options to add a single element or a collection of elements at once. Furthermore, each of the two options has an optional parameter to specify at which position in the list you want to start the addition. Here are some examples.

The simplest list operation is to add a single element to your pets, let’s say a dog, like this:

  1. pets.add("Dog");

When you run the above in jshell you will see the following output:

Output
$4 ==> true

You can disregard $4 here and throughout the tutorial as it is a temporary variable used by jshell. What matters is true which is a confirmation that Dog has been successfully added to your list. In contrast, if you try to add an object other than String, you will get an error. For example, try adding 1 to the list like this:

  1. pets.add(1);

You will see the following error:

Output
| Error: | incompatible types: int cannot be converted to java.lang.String | pets.add(1); | ^

The error is very clear. The pets list should be used only for String objects and a primitive 1 cannot be directly converted to a String. Because of this error, 1 is not added to the list.

Next, try to add another pet to your pet and let it be a valid value, such as a cat. However, out of concern for your cat’s ego, you may want to place the cat before the dog on the list. To do this, you can specify a parameter for the index at which the cat should be added like this:

  1. pets.add(0, "Cat");

The indices of all lists begin at 0. That’s why you specify 0 when you want an element to be added at the first position. Thus, your cat will be the first in your pet’s list.

To confirm your cat is before your dog in the list, you can enter the name of the list pets in jshell and expect the following output:

Output
jshell> pets pets ==> [Cat, Dog]

You can also add multiple entries simultaneously using the method addAll. This method works similarly to add. If you pass one argument, it has to be a collection such as ArrayList. Optionally, you can pass two arguments. The first one then should be the index at which the elements are to be added; the second one should contain the new elements lists. As an exercise, add a new list containing more animals to the pets list using the addAll method.

Altering List Elements

You can alter a list element using the set method and passing two arguments. The first argument is the index, and the second is the value. For example, to restore the dog in front of the list, run the following code:

  1. pets.set(0, "Dog")

When you set Dog at the beginning of the pets list, you practically replace the previous Cat value.

Now your list has two dogs in it and maybe you want to remove one. This can be done with the remove method like this:

  1. pets.remove("Dog")

When you execute the above code in jshell, you will see output such as:

Output
$9 ==> true

The true statement confirms that your operation has succeeded, i.e. that there has been a value Dog and it has been removed. If you try to remove a cat from the list, you will not receive such a confirmation. Instead, you will see false printed because no such element has been found, nor removed.

Finally, if you want to remove all the list elements, you can do so by using the clear method like this:

  1. pets.clear()

After completing the above execution, your pets list will be empty, and you can start adding elements again starting from index 0.

Using Additional List Methods

So far, you have already used some of the most popular list methods such as add(), set(), and remove(). In addition to those mentioned, the List interface includes several other useful methods that can improve the efficiency and accuracy of your code. Below are some of the most significant:

equals Method

The equals method compares two lists to determine their equal. For the lists to be equal, they must be of the same type, size, and corresponding elements. As an example, create two lists with pets - current and desired:

  1. List<String> currentPets = new ArrayList<>();
  1. List<String> desiredPets = new ArrayList<>();

Add a dog element to both lists like this:

  1. currentPets.add("Dog");
  1. desiredPets.add("Dog");

Now you can compare them:

  1. currentPets.equals(desiredPets)

You will get a true response confirming both lists are equal. However, try to add a new element, such as a snake, to the desired pets:

  1. desiredPets.add("Snake")

After that compare the two lists again:

  1. currentPets.equals(desiredPets)

This time you will get a false response because the two lists are not equal.

contains Method

You can search a list for a specific value with the contains method. For example, to check whether the desiredPets list contains a snake, you can write:

  1. desiredPets.contains("Snake")

The output from the above command will print true, thus confirming that there is a snake in the desired pets list.

indexOf Method

You can use the indexOf method to find the position of an item in the list. For example, to find out the position of the dog in the pets list, you can execute:

  1. pets.indexOf("Dog")

The output will show a temporary variable pointing to the position of the item:

Output
$31 ==> 0

The output indicates that the value for Dog has an index of 0, making it the first item in the list. This information can be helpful if you need to use or replace this value.

toString Method

The toString method allows you to retrieve all the elements of a list as a single String, i.e. plain text. This is very useful for debugging or logging purposes. To see how it works, use the method System.out.println for printing output to the console and run in jshell the following command:

  1. System.out.println(pets.toString())

This will print nicely each of your animals in the following format:

Output
[Dog, Fox]

Note that the animals may differ depending on which ones you have added.

forEach Method

The foreach method allows you to iterate through all the elements of the list and execute an action with each of them. This method is an alternative to writing your own foreach loop. The foreach method accepts a Consumer object as an argument. Consumers will be covered in a later tutorial, and a good example will require additional explanation outside the current scope. Still, if you are curious, try to devise your example for the foreach method.

Conclusion

In this tutorial, you learned how to work with Java lists and, more specifically, the ArrayList implementation. You created a list, viewed its elements, and emptied it. You also learned best practices and useful methods for working with lists.

For more on Java, check out our How To Code in Java series.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


Tutorial Series: How To Code in Java

Java is a mature and well-designed programming language with a wide range of uses. One of its unique benefits is that it is cross-platform: once you create a Java program, you can run it on many operating systems, including servers (Linux/Unix), desktop (Windows, macOS, Linux), and mobile operating systems (Android, iOS).

About the authors
Default avatar
Toli

author


Default avatar

Developer Advocate

I’m a Developer Advocate at DigitalOcean with a passion for Serverless and Low-Code Solutions.


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel