Adding arraylist to arraylist in java

Class ArrayList

Type Parameters: E — the type of elements in this list All Implemented Interfaces: Serializable , Cloneable , Iterable , Collection , List , RandomAccess Direct Known Subclasses: AttributeList , RoleList , RoleUnresolvedList

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.)

The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

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

The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Читайте также:  Ширина колонок

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Источник

Add ArrayList to another ArrayList in Java | addAll method

Twitter Facebook Google Pinterest

A quick guide to add one ArrayList values into Another using ArrayList constructor and using addAll() method.

In this post, We will learn How to add ArrayList into a another ArrayList in java.

We can accumulate this in two ways.

1) While creating ArrayList object.
2) Using addAll method.

Add ArrayList to another ArrayList in Java

1) Adding existing ArrayList into new list:

ArrayList has a constructor which takes list as input. Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.

 package com.adeepdrive.arraylist; import java.util.ArrayList; import java.util.List; // Java - W3schools public class AddAnotherList < public static void main(String[] args) < // Creating ArryList - Existing Object ListexistingList = new ArrayList(); existingList.add("America"); existingList.add("New York"); existingList.add("Sidny"); System.out.println("Existing ArrayList Object : " + existingList); // Creating a new ArrayList by passing exiting ArrayList List newList = new ArrayList(existingList); // Printng the new List System.out.println("Newly created ArrayList Object : " + newList); > >

Existing ArrayList Object : [America, New York, Sidny]
Newly created ArrayList Object : [America, New York, Sidny]

First created one ArrayList object as named existingList and added three values to them as America, New York, Sidny. Then printed values of existingList.
Next created another ArrayList object as newList by passing existing existingList and not added any values to it, just printed newList then we see the same values as existingList.

2. How to add using addAll method:

ArrayList has a method named addAll() which is very useful when we do not have access arraylist creation logic (creation implementation is in some jar — third party jar).

public boolean addAll(Collection c)

addAll Example program:

 package com.adeepdrive.arraylist; import java.util.ArrayList; import java.util.List; // Java - W3schools public class AddAnotherListAddAll < public static void main(String[] args) < // getting existing Roles. List existingRoles = getExistingRoles(); // We have new roles in the list. List newUserRoles = new ArrayList(); newUserRoles.add("TimesheetApprove"); newUserRoles.add("LeaveApprove"); newUserRoles.add("CabApprove"); // We have to add new roles to the existing roles then we should go for addAll // method. System.out.println("Printing roles before adding new roles: "+existingRoles); existingRoles.addAll(newUserRoles); System.out.println("Printing roles after adding new roles: "+existingRoles); > // For understanding, I have created new method in the same class. In real time, // this method will be in some jar which is provided by other application // managed by different team. public static List getExistingRoles() < // Creating ArryList - Existing Object ListexistingRoles = new ArrayList(); existingRoles.add("ReadOnly"); existingRoles.add("EmployeLevel"); existingRoles.add("MonitierLevel"); return existingRoles; > >

Printing roles before adding new roles: [ReadOnly, EmployeLevel, MonitierLevel]
Printing roles after adding new roles: [ReadOnly, EmployeLevel, MonitierLevel, TimesheetApprove, LeaveApprove, CabApprove]

Please see the comments given in the above program.
First got all existing roles by calling getExistingRoles method. Then, we have created another new ArrayList object then added new roles to it.
At this point we have two list and values as below.

existingRoles: [ReadOnly, EmployeLevel, MonitierLevel]
newUserRoles: [TimesheetApprove, LeaveApprove, CabApprove]

Next, we want to add newUserRoles to the existingRoles object.

Now observe before and after adding new roles in existingRoles.

Источник

How to Add all the Elements of One ArrayList to Another ArrayList in Java?

Add all the Elements of an ArrayList to another ArrayList

To add all the elements of an ArrayList to this ArrayList in Java, you can use ArrayList.addAll() method. Pass the ArrayList, you would like to add to this ArrayList, as argument to addAll() method.

Following is the syntax to append elements of ArrayList arraylist_2 to this ArrayList arraylist_1 .

arraylist_1.addAll(arraylist_2)

addAll() returns a boolean value if the elements of other ArrayList are appended to this ArrayList.

Example 1 – Append Elements of an ArrayList to this ArrayList

In the following example, we shall take two ArrayLists, arraylist_1 and arraylist_2 , with elements in each of them. And then use addAll() method to append elements of arraylist_2 to arraylist_1 .

Java Program

import java.util.ArrayList; public class ArrayListExample < public static void main(String[] args) < ArrayListarraylist_1 = new ArrayList(); arraylist_1.add("apple"); arraylist_1.add("banana"); ArrayList arraylist_2 = new ArrayList(); arraylist_2.add("mango"); arraylist_2.add("orange"); arraylist_1.addAll(arraylist_2); arraylist_1.forEach(element -> < System.out.println(element); >); > >
apple banana mango orange

Conclusion

In this Java Tutorial, we learned how to append elements of an ArrayList to another, using addAll() method.

Источник

Copy Elements of One ArrayList to Another ArrayList in Java

In this tutorial, we will write a java program to copy elements of one ArrayList to another ArrayList in Java. We will be using addAll() method of ArrayList class to do that.

public boolean addAll(Collection c)

When we call this method like this:

It appends all the elements of oldList to the newList . It throws NullPointerException , if oldList is null.
Note: This method doesn’t clone the ArrayList, instead it appends the elements of one ArrayList to another ArrayList.

Copy elements from one ArrayList to another ArrayList

In the following example, we have an ArrayList al that contains three elements. We have another List list that contains some elements, we are copying the elements of list to the al . This is done using addAll() method, which copies the elements of one List to another another list. This operation doesn’t remove the existing elements of the list, in which the elements are copied.

import java.util.ArrayList; import java.util.List; public class ListToArrayListExample < public static void main(String a[])< ArrayListal = new ArrayList(); //Adding elements to the ArrayList al.add("Text 1"); al.add("Text 2"); al.add("Text 3"); System.out.println("ArrayList Elements are: "+al); //Adding elements to a List List list = new ArrayList(); list.add("Text 4"); list.add("Text 5"); list.add("Text 6"); //Adding all elements of list to ArrayList using addAll al.addAll(list); System.out.println("Updated ArrayList Elements: "+al); > >
ArrayList Elements are: [Text 1, Text 2, Text 3] Updated ArrayList Elements: [Text 1, Text 2, Text 3, Text 4, Text 5, Text 6]

Recommended Articles:

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

@ Himanshu, ArrayList never be a null, instead it is an empty when u create. if you want more clarity, execute the below code. List list = new ArrayList();
List newList = new ArrayList();
list.addAll(newList);
System.out.println(list); // this works fine and creates a list with empty List list = null;
List newList = null;
list.addAll(newList);
System.out.println(list); // this will give you NPE. since List is not initiated with any of its implemented class

Источник

How to Merge Two ArrayLists in Java

Learn to merge two ArrayList into a combined single ArrayList. Also, learn to join ArrayList without duplicates in a combined list instance.

1. Merging Two ArrayLists Retaining All Elements

This approach retains all the elements from both lists, including duplicate elements. The size of the merged list will be arithmetic sum of the sizes of both lists.

The addAll() method is the simplest way to append all of the elements from the given list to the end of another list. Using this method, we can combine multiple lists into a single list.

ArrayList listOne = new ArrayList<>(Arrays.asList("a", "b", "c")); ArrayList listTwo = new ArrayList<>(Arrays.asList("c", "d", "e")); listOne.addAll(listTwo); //Merge both lists System.out.println(listOne); System.out.println(listTwo);

Tip : There are more ways to merge lists using libraries like guava or Apache commons lang, but they all use addAll() method only. So it’s better to use this method directly.

Java 8 streams provide us with one-line solutions to most of the problems and at the same time, the code looks cleaner. Stream’s flatMap() method can be used to get the elements of two or more lists in a single stream, and then collect stream elements to an ArrayList.

Using Stream is recommended as we do not need to modify the original List instances, and we create a third List with elements from both Lists.

ArrayList listOne = new ArrayList<>(Arrays.asList("a", "b", "c")); ArrayList listTwo = new ArrayList<>(Arrays.asList("c", "d", "e")); List combinedList = Stream.of(listOne, listTwo) .flatMap(x -> x.stream()) .collect(Collectors.toList()); System.out.println(combinedList);

In these examples, we combined the lists, but in the final list, we had duplicate elements. This may not be the desired output in many cases. Next, we will learn to merge the lists, excluding duplicates.

2. Merging Two ArrayLists excluding Duplicate Elements

To get a merged list minus duplicate elements, we have two approaches:

The Java Sets allow only unique elements. When we push both lists in a Set and the Set will represent a list of all unique elements combined. In our example, we are using LinkedHashSet because it will preserve the element’s order as well.

ArrayList listOne = new ArrayList<>(Arrays.asList("a", "b", "c")); ArrayList listTwo = new ArrayList<>(Arrays.asList("c", "d", "e")); //Add items from Lists into Set Set set = new LinkedHashSet<>(listOne); set.addAll(listTwo); //Convert Set to ArrayList ArrayList combinedList = new ArrayList<>(set); System.out.println(combinedList);

This is a two-step process, and we can

  • Remove all elements of the first list from the second list,
  • and then add the first list to the second list.

It will give users the combined list without duplicate elements.

ArrayList listOne = new ArrayList<>(Arrays.asList("a", "b", "c")); ArrayList listTwo = new ArrayList<>(Arrays.asList("c", "d", "e")); List listTwoCopy = new ArrayList<>(listTwo); listTwoCopy.removeAll(listOne); listOne.addAll(listTwoCopy); System.out.println(listOne);

Источник

Оцените статью