简体   繁体   中英

Add all the elements of multiple ArrayList objects into a single ArrayList object

In my case I have 4 ArrayList objects as below:

ArrayList<MyProduct> lstStyle;
ArrayList<MyProduct> 2ndStyle;
ArrayList<MyProduct> 3rdStyle;
ArrayList<MyProduct> 4thStyle;

I want to add all the elements in each ArrayList into a new ArrayList called Style .

ArrayList<MyProduct> Style;

Can I do this without looping each ArrayList?

Use the List#addAll(Collection c) method

Style.addAll(lstStyle);
Style.addAll(2ndStyle);
Style.addAll(3rdStyle);
Style.addAll(4thStyle);

Ofcourse, you need to instantiate all the lists first, otherwise you'll face a NullPointerException .

Collections.addAll(Style, lstStyle, 2ndStyle, 3rdStyle, 34thStyle);

Use addAll method

ArrayList<MyProduct> Style;

 Style.addAll(lstStyle);
 Style.addAll(2ndStyle);
 Style.addAll(3rdStyle);
 Style.addAll(4thStyle);  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM