Write a java program to manipulate ArrayLists

Write a program that performs the following actions:

  1. Read 2n integers as input.
  2. Create two arraylists to store n elements in each arraylist.
  3. Write a function  generateOddEvenList which accepts this two arraylist as input.
  4. The function fetch the odd index elements from first array list and even index elements from second array list and add them to a new array list according to their index.
  5. Return the arraylist.

Note:

– The index of the first element is 0.

– Consider 0 as an even number.

– Maintain order in the output array list

Input and Output Format:

Input consists of 2n+1 integers. The first integer denotes the size of the arraylist, the next n integers are values to the first arraylist, and the last n integers are values to the second arraylist.

Output consists of a modified arraylist as per step 4.

Refer sample output for formatting specifications.

Sample Input 1:

5

12

13

14

15

16

2

3

4

5

6

Sample Output 1:

2

13

4

15

6

 Java program to manipulate ArrayLists.

package testCases;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class MainJava {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int s = Integer.parseInt(sc.nextLine());
ArrayList<Integer> al1 = new ArrayList<Integer>();
ArrayList<Integer> al2 = new ArrayList<Integer>();
for (int i = 0; i < s; i++)
al1.add(sc.nextInt());
for (int i = 0; i < s; i++)
al2.add(sc.nextInt());
ArrayList<Integer> al3 = new ArrayList<Integer>();
al3 = display(al1, al2);
Iterator<Integer> it = al3.iterator();
while (it.hasNext()) {
int n = it.next();
System.out.println(n);
}
}
public static ArrayList<Integer> display(ArrayList<Integer> al1, ArrayList<Integer> al2) {
ArrayList<Integer> al3 = new ArrayList<Integer>();
for (int i = 0; i < al1.size(); i++) {
if (i % 2 == 0)
al3.add(al2.get(i));
else
al3.add(al1.get(i));
}
return al3;
}
}

 

Add a Comment

Your email address will not be published. Required fields are marked *

4 − one =