How to add list to list java

How to add list to list java

Java List add() and addAll() Methods

How to add list to list java. Смотреть фото How to add list to list java. Смотреть картинку How to add list to list java. Картинка про How to add list to list java. Фото How to add list to list java

How to add list to list java. Смотреть фото How to add list to list java. Смотреть картинку How to add list to list java. Картинка про How to add list to list java. Фото How to add list to list java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

1. Java List add()

This method is used to add elements to the list. There are two methods to add elements to the list.

Let’s look at some examples of List add() methods.

Recommended Readings:

2. Java List addAll()

This method is used to add the elements from a collection to the list. There are two overloaded addAll() methods.

Let’s look at a simple example of List addAll() methods.

3. UnsupportedOperationException with List add() Methods

If you look at the List add() and addAll() method documentation, the operation is mentioned as optional. It means that the list implementation may not support it. In this case, the list add() methods throw UnsupportedOperationException. There are two common scenarios where you will find this exception when adding elements to the list.

Let’s look at a simple example of UnsupportedOperationException with add operation of both these types of lists.

How to add list to list java. Смотреть фото How to add list to list java. Смотреть картинку How to add list to list java. Картинка про How to add list to list java. Фото How to add list to list javaJava List add() UnsupportedOperationException

References

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

How to add list to list java

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.

This interface is a member of the Java Collections Framework.

Java List

Jakob Jenkov
Last update: 2020-02-29

Java List Tutorial Video

If you prefer to watch a video instead of reading text, here is a video version of this Java List tutorial:

List vs. Set

The Java List and Java Set interfaces are quite similar in that they both represents a collection of elements. However, there are some significant differences. These differences are reflected in the methods the List and Set interfaces offer.

The second difference between a Java List and Java Set interfaces is, that the elements in a List has an order, and the elements can be iterated in that order. A Java Set does not make any promises about the order of the elements kept internally.

List Implementations

Being a Collection subtype all methods in the Collection interface are also available in the List interface.

Since List is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following List implementations in the Java Collections API:

Of these implementations, the ArrayList is the most commonly used.

Create a List

You create a List instance by creating an instance of one of the classes that implements the List interface. Here are a few examples of how to create a List instance:

Remember, most often you will use the ArrayList class, but there can be cases where using one of the other implementations might make sense.

Generic Lists

This List can now only have MyObject instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks:

Without generics the example above would have looked like this:

Notice how it is necessary to cast the MyObject instances retrieved from the List to MyObject. Without a generic type set on the List variable declaration the Java compiler only knows that the List contains Object instances. Thus, you need to cast them to the concrete class (or interface) that you know the object to be of.

Throughout the rest of this Java List tutorial I will be using generic List examples as much as possible.

For more information about Java Generics, see the Java Generics Tutorial.

Insert Elements in a Java List

You insert elements (objects) into a Java List using its add() method. Here is an example of adding elements to a Java List using the add() method:

The first three add() calls add a String instance to the end of the list.

Insert null Values

Insert Elements at Specific Index

It is possible to insert an element into a Java List at a specific index. The List interface has a version of the add() method that takes an index as first parameter, and the element to insert as the second parameter. Here is an example of inserting an element at index 0 into a Java List :

If the List already contained elements, these elements will now get pushed further down in the List ‘s internal sequence. The element that had index 0 before the new element was inserted at index 0, will get pushed to index 1 etc.

Insert All Elements From One List Into Another

Get Elements From a Java List

You can get the elements from a Java List using the index of the elements. You can do so using either the get(int index) method. Here is an example of accessing the elements of a Java List using the element indexes:

It is also possible to iterate the elements of a Java List in the order they are stored in internally. I will show you how to do that later in this Java List tutorial.

Find Elements in a List

You can find elements in a Java List using one of these two methods:

The indexOf() method finds the index of the first occurrence in the List of the given element. Here is an example finding the index of two elements in a Java List :

Running this code will result in this output:

Find Last Occurrence of Element in a List

The lastIndexOf() method finds the index of the last occurrence in the List of a given element. Here is an example showing how to find the index of the last occurrence of a given element in a Java List :

The output printed from running the above Java example will be:

Checking if List Contains Element

You can check if a Java List contains a given element using the List contains() method. Here is an example of checking if a Java List contains an element using the contains() method:

The output from running this Java List example will be:

. because the List does actually contain the element.

To determine if the List contains the element, the List will internally iterate its elements and compare each element to the object passed as parameter. The comparison uses the Java equals method of the element to check if the element is equal to the parameter.

Remove Elements From a Java List

You can remove elements from a Java List via these two methods:

remove(Object element) removes that element in the list, if it is present. All subsequent elements in the list are then moved up in the list. Their index thus decreases by 1. Here is an example of removing an element from a Java List based on the element itself:

This example first adds an element to a List and then removes it again.

The List remove(int index) method removes the element at the given index. All subsequent elements in the list are then moved up in the list. Their index thus decreases by 1. Here is an example of removing an element from a Java List by its index:

Remove All Elements From a Java List

Retain All Elements From One List in Another

List Size

You can obtain the number of elements in the List by calling the size() method. Here is an example:

Sublist of List

The subList() method takes 2 parameters: A start index and and end index. The start index is the index of the first element from the original List to include in the sublist. The end index is the last index of the sublist, but the element at the last index is not included in the sublist. This is similar to how the Java String substring method works.

Here is a Java example of creating a sublist of elements from another List using the subList() method:

After executing the list.subList(1,3) instruction the sublist will contain the elements at index 1 and 2. Remember, the original list has 4 elements with indexes from 0 to 3. The list.subList(1,3) call will include index 1, but exclude index 3, thereby keeping the elements at index 1 and 2.

Convert List to Set

Convert List to Array

You can convert a Java List to a Java Array using the List toArray() method. Here is an example of converting a Java List to a Java array:

It is also possible to convert a List to an array of a specific type. Here is an example of converting a Java List to an array of a specific type:

Convert Array to List

It is also possible to convert a Java List to an array. Here is an example of converting a Java array to a List :

Sort List

You can sort a Java List using the Collections sort() method. I have explained how that works in my sorting Java collections tutorial, but I will just show you a few ways to sort a Java List in the following sections.

Sort List of Comparable Objects

If the List contains objects that implement the Comparable interface ( java.lang.Comparable ), then the objects can compare themselves to each other. In that case you can sort the List like this:

The Java String class implements the Comparable interface, you can sort them in their natural order, using the Collections sort() method.

Sort List Using Comparator

Here is the code that sorts a Java List of the above Car objects:

Notice the Comparator implementation in the example above. This implementation only compares the brand field of the Car objects. It is possible to create another Comparator implementation which compares the number plates, or even the number of doors in the cars.

Note too, that it is possible to implement a Comparator using a Java Lambda. Here is an example that sorts a List of Car objects using three different Java lambda implementations of the Comparator interface, each of which compares Car instances by a different field:

Iterate List

You can iterate a Java List in several different ways. The three most common ways are:

I will explain each of these methods of iterating a Java List in the following sections.

Iterate List Using Iterator

The first way to iterate a List is to use a Java Iterator. Here is an example of iterating a List with an Iterator :

You obtain an Iterator by calling the iterator() method of the List interface.

If the List is typed using Java Generics you can save some object casting inside the while loop. Here is an example:

Iterate List Using For-Each Loop

The second way to iterate a List is to use the for loop added in Java 5 (also called a «for each» loop). Here is an example of iterating a List using the for loop:

If the list is typed (a generic List ) you can change the type of the variable inside the for loop. Here is typed List iteration example:

Iterate List Using For Loop

The third way to iterate a List is to use a standard for loop like this:

The for loop creates an int variable and initializes it to 0. Then it loops as long as the int variable i is less than the size of the list. For each iteration the variable i is incremented.

Inside the for loop the example accesses the elements in the List via its get() method, passing the incrementing variable i as parameter.

Iterate List Using Java Stream API

Once you have obtained a Stream from a List you can iterate the Stream by calling its forEach() method. Here is an example of iterating the elements of a List using the Stream forEach() method:

You can read more about the many different options available for processing the elements of a List via the Java Stream API in my Java Stream API Tutorial.

More Details in the Java List JavaDoc

The List Interface

Collection Operations

Here’s a nondestructive form of this idiom, which produces a third List consisting of the second list appended to the first.

Note that the idiom, in its nondestructive form, takes advantage of ArrayList ‘s standard conversion constructor.

And here’s an example (JDK 8 and later) that aggregates some names into a List :

Like the Set interface, List strengthens the requirements on the equals and hashCode methods so that two List objects can be compared for logical equality without regard to their implementation classes. Two List objects are equal if they contain the same elements in the same order.

Positional Access and Search Operations

The addAll operation inserts all the elements of the specified Collection starting at the specified position. The elements are inserted in the order they are returned by the specified Collection ‘s iterator. This call is the positional access analog of Collection ‘s addAll operation.

This algorithm, which is included in the Java platform’s Collections class, randomly permutes the specified list using the specified source of randomness. It’s a bit subtle: It runs up the list from the bottom, repeatedly swapping a randomly selected element into the current position. Unlike most naive attempts at shuffling, it’s fair (all permutations occur with equal likelihood, assuming an unbiased source of randomness) and fast (requiring exactly list.size()-1 swaps). The following program uses this algorithm to print the words in its argument list in random order.

Iterators

ListIterator interface follows.

Here’s the standard idiom for iterating backward through a list.

How to add list to list java. Смотреть фото How to add list to list java. Смотреть картинку How to add list to list java. Картинка про How to add list to list java. Фото How to add list to list java

The five possible cursor positions.

Note that the indexOf method returns it.previousIndex() even though it is traversing the list in the forward direction. The reason is that it.nextIndex() would return the index of the element we are about to examine, and we want to return the index of the element we just examined.

The add method inserts a new element into the list immediately before the current cursor position. This method is illustrated in the following polymorphic algorithm to replace all occurrences of a specified value with the sequence of values contained in the specified list.

Range-View Operation

As the term view implies, the returned List is backed up by the List on which subList was called, so changes in the former are reflected in the latter.

Similar idioms can be constructed to search for an element in a range.

Here’s a polymorphic algorithm whose implementation uses subList to deal a hand from a deck. That is, it returns a new List (the «hand») containing the specified number of elements taken from the end of the specified List (the «deck»). The elements returned in the hand are removed from the deck.

The following is a program that uses the dealHand method in combination with Collections.shuffle to generate hands from a normal 52-card deck. The program takes two command-line arguments: (1) the number of hands to deal and (2) the number of cards in each hand.

Running the program produces output like the following.

List Algorithms

Java List Collection Tutorial and Examples

Table of content:

1. Overview of List collection

How to add list to list java. Смотреть фото How to add list to list java. Смотреть картинку How to add list to list java. Картинка про How to add list to list java. Фото How to add list to list java

A list can store objects of any types. Primitive types are automatically converted to corresponding wrapper types, e.g. integer numbers are converted to Integer objects. It allows null and duplicate elements, and orders them by their insertion order (index).

The following class diagram depicts the primary methods defined in the java.util.List interface:

How to add list to list java. Смотреть фото How to add list to list java. Смотреть картинку How to add list to list java. Картинка про How to add list to list java. Фото How to add list to list java

The List is the base interface for all list types, and the ArrayList and LinkedList classes are two common List ’s implementations.

How to add list to list java. Смотреть фото How to add list to list java. Смотреть картинку How to add list to list java. Картинка про How to add list to list java. Фото How to add list to list java

The following is a quick example of creating a new ArrayList and LinkedList which hold String objects; add some elements to them; and then print out the collections:

2. Creating a new list

Since Java 7, we can remove the type parameter on the right side as follows:

The compiler is able to infer the actual type parameter from the declaration on the left side.

Since Java 10, you can shorten the declaration of a List collection by using the var reserved word like this:

The compiler can infer the type of the variable on the left based on the object type on the right side. And var can be used to declare local variables only.

When creating a new ArrayList using the empty constructor, the list is constructed with an initial capacity of ten. If you are sure how many elements will be added to the list, it’s recommended to specify a capacity which is large enough. Let’s say, if we know that a list contains around 1000 elements, declare the list as follows:

It’s also possible to construct a list that takes elements from an existing collection, for example:

3. Basic List operations: adding, retrieving, updating, removing elements

Adding elements of sub types of the declared type:

We can insert an element into the list at a specified index, for example:

That inserts the String “Four” at the 2nd position in the list.

We can also add all elements of an existing collection to the end of the list:

Or add the elements to the list at a specified position:

That inserts all elements of the listWords collection at 3 rd position of the listStrings collection.

Retrieving elements from a List

The get() method is used to retrieve an element from the list at a specified index. For example, the following code gets an element at 2 nd position in the array list and an element at 4 th position in the linked list:

For a LinkedList implementation, we can get the first and the last elements like this:

Note that the getFirst() and getLast() methods are specific to the LinkedList class.

Updating elements in a List

Use the set(index, element) method to replace the element at the specified index by the specified element. For example:

That replaces the 3 rd element in the list by the new String “Hi”.

Removing elements from a List

To remove an element from the list, use the remove(index) or remove(Object) method which removes the element at the specified index or by object reference. For example:

To remove all elements in the list, use the clear() method:

4. Iterating over elements in a list

Or use an iterator like this:

For more list-specific, use a list iterator as shown below:

Since Java 8, we can use the forEach() method like this:

For more details and examples, see the tutorial: Java Collections Looping Example

For more about the forEach iteration method, see the tutorial: The 4 Methods for Iterating Collections in Java

5. Searching for an element in a list

Note that the above methods compare the elements using their equals() method, so if you define your own type, make sure it implements the equals() method correctly.

6. Sorting a list

Note that all elements in the list must implement the Comparable interface, so if you define your own type, make sure it implements that interface and its compareTo() method.

Since Java 8, the List interface introduces the sort() method, so you can sort elements in an ArrayList or LinnkedList directly like this:

For more details and examples, see the article: Sorting List Collections Examples

7. Copying elements from one list into another

The output would be:

8. Shuffling elements in a list

The output would be:

9. Reversing elements in a list

The output would be:

10. Extracting a portion of a list

Note that the sub list is just a view of the original list, so any modifications made on the original list will reflect in the sub list.

11. Converting between Lists and arrays

And the List interface provides the toArray() method that returns an array of Objects containing all of the elements in the list in proper sequence (from first to last element). Here’s an example:

Note that the returned array contains copies of elements in the list, which that means we can safely modify the array without affecting the list.

12. List to Stream

List.stream() : returns a sequential stream.

List.parallelStream() : returns a possibly parallel stream.

For example, the following code converts a List numbers to a stream and uses the Stream API to calculate the sum of all numbers:

For more information about Java stream, read Understand Java Stream API.

13. Concurrent lists

Note that you must manually synchronize the returned list when iterating over it, for example:

Conclusion:

For hands-on practice on Java list collection, I recommend you to watch this video tutorial:

Related Java List tutorials:

Other Java Collections Tutorials:

API References for Java List:

About the Author:

How to add list to list java. Смотреть фото How to add list to list java. Смотреть картинку How to add list to list java. Картинка про How to add list to list java. Фото How to add list to list javaNam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *