Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat two ArrayLists?

I have two ArrayLists 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?

like image 911
Anirudh Avatar asked Dec 24 '12 06:12

Anirudh


People also ask

How do you concatenate ArrayLists?

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.

How do I make two ArrayLists equal each other?

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().

Which ArrayList function is used to combine two ArrayLists?

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.

How do you concatenate a String in an ArrayList in Java?

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.


1 Answers

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"] 
like image 135
Cat Avatar answered Oct 02 '22 14:10

Cat