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?
This question is related to
java
arraylist
concatenation
concat
If you want to do it one line and you do not want to change list1 or list2 you can do it using stream
List<String> list1 = Arrays.asList("London", "Paris");
List<String> list2 = Arrays.asList("Moscow", "Tver");
List<String> list = Stream.concat(list1.stream(),list2.stream()).collect(Collectors.toList());
ArrayList<String> resultList = new ArrayList<String>();
resultList.addAll(arrayList1);
resultList.addAll(arrayList2);
for a lightweight list that does not copy the entries, you may use sth like this:
List<Object> mergedList = new ConcatList<>(list1, list2);
here the implementation:
public class ConcatList<E> extends AbstractList<E> {
private final List<E> list1;
private final List<E> list2;
public ConcatList(final List<E> list1, final List<E> list2) {
this.list1 = list1;
this.list2 = list2;
}
@Override
public E get(final int index) {
return getList(index).get(getListIndex(index));
}
@Override
public E set(final int index, final E element) {
return getList(index).set(getListIndex(index), element);
}
@Override
public void add(final int index, final E element) {
getList(index).add(getListIndex(index), element);
}
@Override
public E remove(final int index) {
return getList(index).remove(getListIndex(index));
}
@Override
public int size() {
return list1.size() + list2.size();
}
@Override
public void clear() {
list1.clear();
list2.clear();
}
private int getListIndex(final int index) {
final int size1 = list1.size();
return index >= size1 ? index - size1 : index;
}
private List<E> getList(final int index) {
return index >= list1.size() ? list2 : list1;
}
}
One ArrayList1 add to data,
mArrayList1.add(data);
and Second ArrayList2 to add other data,
mArrayList2.addAll(mArrayList1);
add one ArrayList to second ArrayList as:
Arraylist1.addAll(Arraylist2);
EDIT : if you want to Create new ArrayList from two existing ArrayList then do as:
ArrayList<String> arraylist3=new ArrayList<String>();
arraylist3.addAll(Arraylist1); // add first arraylist
arraylist3.addAll(Arraylist2); // add Second arraylist
var arr3 = new arraylist();
for(int i=0, j=0, k=0; i<arr1.size()+arr2.size(); i++){
if(i&1)
arr3.add(arr1[j++]);
else
arr3.add(arr2[k++]);
}
as you say, "the names and numbers beside each other".
Source: Stackoverflow.com