Create two Lists, one is ArrayList and the other one is LinkedList and fill it using 10 state names (e.g., Texas). Sort the list and print it, and then shuffle the lists at random. Please use java.util.Collections class to do sorting and shuffling.

Respuesta :

Answer:

The program to this question can be given as:

Program:

import java.util.*; //import package

public class Main //define class main.

{

public static void main(String[] args) //define main method.

{

ArrayList<String> AL1 = new ArrayList<>(); //create ArrayList object AL1.

LinkedList<String> LL2 = new LinkedList<>(); //create LinkedList object LL2.

AL1.addAll(Arrays.asList("Bihar","Andhra Pradesh","Assam","Chhattisgarh","Arunachal Pradesh","Goa","west bangol","Gujarat","Jharkhand","Karal"));//add elements in ArrayList

LL2.addAll(Arrays.asList("Bihar","Andhra Pradesh","Assam","Chhattisgarh","Arunachal Pradesh","Goa","west bangol","Gujarat","Jharkhand","Karal"));//add elements in LinkedList

Collections.sort(AL1); //sort ArrayList

Collections.sort(LL2); //sort LinkedList

System.out.println("Sorting in ArrayList and LinkedList elements :");

System.out.println("ArrayList :\n" +AL1);

System.out.println("LinkedList :\n"+LL2);

Collections.shuffle(AL1); //shuffle ArrayList

Collections.shuffle(LL2); //shuffle LinkedList

System.out.println("shuffling in ArrayList and LinkedList elements :");

System.out.println("shuffle ArrayList:\n"+AL1);

System.out.println("shuffle LinkedList:\n"+LL2);

}

}

Output:

Sorting in ArrayList and LinkedList elements :

ArrayList :

[Andhra Pradesh, Arunachal Pradesh, Assam, Bihar, Chhattisgarh, Goa, Gujarat, Jharkhand, Karal, west bangol]

LinkedList :

[Andhra Pradesh, Arunachal Pradesh, Assam, Bihar, Chhattisgarh, Goa, Gujarat, Jharkhand, Karal, west bangol]

shuffling in ArrayList and LinkedList elements :

shuffle ArrayList:

[Chhattisgarh, Jharkhand, Gujarat, Goa, west bangol, Andhra Pradesh, Arunachal Pradesh, Assam, Karal, Bihar]

shuffle LinkedList:

[Assam, Karal, Jharkhand, Bihar, Goa, Arunachal Pradesh, Andhra Pradesh, Gujarat, west bangol, Chhattisgarh]

Explanation:

In the above java program firstly we import the package then we define the main method in this method we create the ArrayList and LinkedList object that is AL1 and LL2.

In ArrayList and LinkedList we add state names then we use the sort and shuffle function. and print all values.

  • The sort function is used to sort array by name.
  • The shuffle function is used to Switching the specified list elements randomly.