Home CPSC 240

Lab 2: Using Arraylists



To practice making Arraylists of objects and using String methods



For this lab, you will write a program which reads in a list of names and prints them out in a different format. Names will be read in using a "Lastname, Firstname" format such as "Smith, Alice". They should be printed out using the more familiar "Firstname Lastname" format, such as "Alice Smith".

The names should also be printed out in alphabetical order, by last name. In order to accomplish this, you will need to be read them into an Arraylist, then sort them, and then swap the first and last names.

Note that both first names (such as "Billy Joe") and last names (such as "van Dijk") can have spaces in them. Furthermore, the sorting by last name should be done regardless of case. So the last name "van Dijk" should come before that of "Walters". In order to do this, you can pass an extra parameter to Collections.sort:

Collections.sort(names, String.CASE_INSENSITIVE_ORDER);



  1. Begin by creating an Arraylist of String objects.
  2. Next, make a Scanner and write a loop that reads in Strings from the user until they provide an empty String as input. For each string read in, add it to the list.
  3. Sort the list of names. Don't forget to ignore case differences.
  4. Loop through the list of names. For each one, get the first name and last name out of the string. You can do this using the String class's indexOf and substring methods. Store the new String on top of the old one in the Arraylist.
  5. For each name, print out the first and last names. Also include the number the name is in the sorted order (counting from 1).


Example Run

If your program is given the following input:

Smith, Mark
Robertson, Anna Lee
de la Cruz, Maria
Anderson, Louis
Thompson, Zoe
Clark, Paul

Then it should produce the following output:

1. Louis Anderson
2. Paul Clark
3. Maria de la Cruz
4. Anna Lee Robertson
5. Mark Smith
6. Zoe Thompson



When you are done, please submit the Java code under the assignment in Canvas.



A solution to this lab can be found in Roster.java.

Copyright © 2023 Ian Finlayson | Licensed under a Attribution-NonCommercial 4.0 International License.