Write a java program for Array List Merging and Sorting

Write a code to read two int array lists of size 5 each as input and to merge the two arrayLists, sort the merged array list in ascending order and fetch the elements at 2nd, 6th and 8th index into a new ArrayList and return the final ArrayList.The return type is an ArrayList with elements from 2,6 and 8th index

The return type is an ArrayList with elements from 2,6 and 8th index position.Array index starts from position 0.

Create the  Main class which gets two array list of size 5 as input and call the static methodsortMergedArrayList present in the UserMainCode.

Input and Output Format:

Input consists of two array lists of size 5.

The output is an array list.

Note – The first element is at index 0.

Refer sample output for formatting specifications.

Sample Input 1:

3

1

17

11

19

5

2

7

6

20

Sample Output 1:

3

11

19

Sample Input 2:

1

2

3

4

5

6

7

8

9

10

Sample Output 2:

3

7

9

Array List Merging and Sorting in Java.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
ArrayList<Integer> al1=new ArrayList<Integer>();
ArrayList<Integer> al2=new ArrayList<Integer>();
ArrayList<Integer> ans=new ArrayList<Integer>();
for(int i=0;i<5;i++)
al1.add(sc.nextInt());
for(int j=0;j<5;j++)
al2.add(sc.nextInt());
ans=Main1.answer(al1,al2);
//System.out.println(ans);
for(int k=0;k<3;k++)
System.out.println(ans.get(k));
}
}
 class Main1 {
public static ArrayList<Integer> answer (ArrayList<Integer> al1, ArrayList<Integer> al2)
{
al1.addAll(al2);
Collections.sort(al1);
ArrayList<Integer> ans=new ArrayList<Integer>();
ans.add(al1.get(2));
ans.add(al1.get(6));
ans.add(al1.get(8));
return ans;
}
 }

Add a Comment

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

eleven − 7 =