I have two ArrayList
s of equal size. List 1 consists of 10 names and list 2 consists of their phone numbers.
I want to concat the names and number into one ArrayList
. How do I do this?
Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.
Step 1: Declare the ArrayList 1 and add the values to it. Step 2: Create another ArrayList 2 with the same type. Step 3: Now, simply add the values from one ArrayList to another by using the method addAll().
addAll() 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.
extends E> c) method of the class java. util. ArrayList appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. Using this method you can concatenate two lists.
You can use .addAll()
to add the elements of the second list to the first:
array1.addAll(array2);
Edit: Based on your clarification above ("i want a single String in the new Arraylist which has both name and number."), you would want to loop through the first list and append the item from the second list to it.
Something like this:
int length = array1.size(); if (length != array2.size()) { // Too many names, or too many numbers // Fail } ArrayList<String> array3 = new ArrayList<String>(length); // Make a new list for (int i = 0; i < length; i++) { // Loop through every name/phone number combo array3.add(array1.get(i) + " " + array2.get(i)); // Concat the two, and add it }
If you put in:
array1 : ["a", "b", "c"] array2 : ["1", "2", "3"]
You will get:
array3 : ["a 1", "b 2", "c 3"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With