I need help with this Java programming assignment (please meet all the requireme
ID: 3909767 • Letter: I
Question
I need help with this Java programming assignment (please meet all the requirements):
Create an array of six USA state names using the array initializer syntax. Then, create an ArrayList from this array. Add two more state names to this list, and then use a foreach loop to display the state names all on one line separated by spaces. Next, use the Collections class to sort the list, and display the sorted list with a foreach loop as before. Display the 5th element in the sorted list. Delete the state at index 6 and identify which state was removed. Finally, use a for loop to display the list in its final form, all elements on one line separated by spaces. See Sample Output below.
Sample Output
States I entered
Florida Vermont Oregon Virginia Kansas Arizona Texas New York
States list sorted
Arizona Florida Kansas New York Oregon Texas Vermont Virginia
The 5th state in my list is Oregon
Deleted state Vermont
Here is my final list of states
Arizona Florida Kansas New York Oregon Texas Virginia
Explanation / Answer
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Test
{
public static void main(String[] args)
{
String[] arr= {"Florida","Vermont","Oregon","Virginia","Kansas","Arizona"};
ArrayList<String> list =new ArrayList<String>(Arrays.asList(arr));
list.add("Texas");
list.add("New York");
System.out.println("The list of states is:");
for(String s:list)
System.out.print(s+" ");
System.out.println();
Collections.sort(list);
System.out.println("Sorted List is given below");
for(String s:list)
System.out.print(s+" ");
System.out.println();
System.out.println("5th element is "+list.get(4));
list.remove("Oregon");
System.out.println("Final list is:");
for(String s:list)
System.out.print(s+" ");
}
}
The output is
The list of states is:
Florida Vermont Oregon Virginia Kansas Arizona Texas New York
Sorted List is given below
Arizona Florida Kansas New York Oregon Texas Vermont Virginia
5th element is Oregon
Final list is:
Arizona Florida Kansas New York Texas Vermont Virginia
Do give a thumbs up