Get startedGet started for free

Displaying city names

Managing sets of locations is a common task in applications like travel planning, navigation systems, or user-generated location sets. In this exercise, you will practice using an enhanced for-loop to display a set of cities. This approach ensures you can easily retrieve and process city names from a collection.

This exercise is part of the course

Input/Output and Streams in Java

View Course

Exercise instructions

  • Use enhanced for-loop to travel through the created set cities.
  • Print each city inside the loop.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

import java.util.HashSet;

public class CityDisplay {
    public static void main(String[] args) {
        HashSet cities = new HashSet<>();

        cities.add("New York");
        cities.add("Los Angeles");
        cities.add("Chicago");

        // Use enhanced for-loop
        for (____ city: ____) {
         	// Print each city name inside the set
            System.out.println(____);
        }
    }
}
Edit and Run Code