Java merge two lists and sort

Write a code to read two int array lists of size 5 each as input and to merge the two ArrayList, 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 the 2,6 and 8th index positions. Array index starts from position 0.

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

Following are the steps we will use to merge and sort ArrayList:

  • Create three array lists of integer types.
  • Add elements to two lists.
  • Now, call the answer[] method of Main1 class with both the array list.
  • Now, we will add the element of the second list to the first by using the addAll[] method.
  • Just create one more list, and get the element from the specified position from the first list and add it to the newly created list. And return it.
  • At last, just iterate over it and get all the elements.
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 al1=new ArrayList[]; ArrayList al2=new ArrayList[]; ArrayList ans=new ArrayList[]; for[int i=0;i

Chủ Đề