Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selection of First L Items of ArrayList of size N > L and Insertion to Another ArrayList in Java

Tags:

java

arraylist

I have an ArrayList l1 of size N and another l2 of size L < N. I want to put the L first items of l1 to l2. I thought to use the for loop of type for(Object obj : l1) to scan my list of size N and then use l2.add(obj) to add elements on l2, but I am not sure if when I reach the max size of l2 (i.e. L) stops inserting items or continues.

Could somebody suggest me a way to do that? Thanx

like image 698
NewJavaStudent Avatar asked Aug 19 '13 12:08

NewJavaStudent


People also ask

How do you add an ArrayList to another ArrayList?

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 move an element from one ArrayList to another?

In order to copy elements of ArrayList to another ArrayList, we use the Collections. copy() method. It is used to copy all elements of a collection into another.

Can you set an ArrayList equal to another ArrayList?

We can also change one value of one ArrayList and can look for the same in the other one whether it is changed or not. Syntax : ArrayList<Integer> gfg=new ArrayList<>(); ArrayList<Integer> gfg2=new ArrayList<>(gfg);

How do you make an ArrayList a specific size?

To create an ArrayList of specific size, you can pass the size as argument to ArrayList constructor while creating the new ArrayList. Following the syntax to create an ArrayList with specific size. myList = new ArrayList<T>(N); where N is the capacity with which ArrayList is created.


1 Answers

You can use List.subList(int, int) method to get the first L items

int L = 2;

List<String> newList = new ArrayList<>(inputList.subList(0,L));
like image 176
sanbhat Avatar answered Sep 30 '22 18:09

sanbhat