CodeGym /Courses /Java Syntax /List of all collections

List of all collections

Java Syntax
Level 8 , Lesson 2
Available

"Hi, Amigo."

"Hey, Rishi."

"Ellie told me you wanted more examples of collections. I'll give you a few. Here is a list of collections and interfaces:"

Interface Class/implementation Description
List  ArrayList  List
 LinkedList  List
 Vector  Vector
 Stack  Stack
 Set    HashSet  Set
 TreeSet  Set
 SortedSet  Sorted set
Map  HashMap Map/dictionary
 TreeMap  Map/dictionary
 SortedMap  Sorted dictionary
 Hashtable  Hash-table

"Hmm. That's quite a lot. Four lists, three sets, and four maps."

"Yes, they are all different implementations of the List, Set and Map interfaces."

" What's the difference between these implementations?"

"That's exactly what we're going to talk about today. Just be patient."

"Do you have any other questions?"

" I know how to display a list on the screen. How do I display a Set or Map?"

"The elements of a List have a set order, so you can just use an index to display them. For a Set or Map, there is no specific order. In fact, the order of their elements can change as items are deleted or new items are added."

"Amazing."

"This is why special objects, called iterators, were invented to work with collection elements. They let you to go through all the elements in a collection, even if they have only names instead of indices (Map), or neither names nor indices (Set)."

"Here are some examples:"

Display elements of a Set
 public static void main(String[] args)
{
    Set&ltString> set = new HashSet&ltString>();
    set.add("Rain");
    set.add("In");
    set.add("Spain");

     // Get an iterator for the set
     Iterator&ltString> iterator = set.iterator();

    while (iterator.hasNext())        // Check if there is another element
    {
       // Get the current element and move to the next one
       String text = iterator.next();

        System.out.println(text);
    }
}
 
8
Task
New Java Syntax, level 8, lesson 2
Locked
Where does a Person come from?
Where does a Person come from?
Display elements of a List
public static void main(String[] args)
{
    List&ltString> list = new ArrayList&ltString>();
    list.add("Rain");
    list.add("In");
    list.add("Spain");

    Iterator&ltString> iterator = list.iterator();// Get an iterator for the list

    while (iterator.hasNext())      // Check if there is another element   
    {
        // Get the current element and move to the next one
        String text = iterator.next();

        System.out.println(text);
    }
}
Display elements of a Map
public static void main(String[] args)
{
    // All elements are stored in pairs
    Map<String, String> map = new HashMap<String, String>();
    map.put("first", "Rain");
    map.put("second", "In");
    map.put("third", "Spain");

    Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();

   while (iterator.hasNext())
    {
        // Get a key-value pair
        Map.Entry<String, String> pair = iterator.next();
        String key = pair.getKey();            // Key
        String value = pair.getValue();        // Value
        System.out.println(key + ":" + value);
    }
}

"Wow. I wonder what all that means."

"It's actually quite simple. First, we get a special object, an iterator, from the collection. The iterator has only two methods.

1. The next() method returns the next element in the collection.

2. The hasNext() method checks whether there are still elements that have not been returned by next()."

"OK. I think it's getting clearer now. Let me try to repeat back to you what I understood."

"So... First, we need to call the iterator() method on a collection to get this magic iterator object."

"Then we get elements one by one as long as there are any left to get. We get the next element in the collection by calling next(), and we check whether there are still elements in the collection by calling hasNext() on the iterator. Is that correct?"

"Yes, more or less. But wait for the good part."

"Java has shorthand notation for working with iterators. Following the pattern of while and for, one more special statement has been added: for each. It is also indicated using the keyword for."

"The for-each statement is only used for working with collections and containers. It uses an iterator implicitly, but we only see the returned element."

"Let me show you the longhand and shorthand ways to work with an iterator:"

Longhand
public static void main(String[] args)
{
  Set&ltString> set = new HashSet&ltString>();
    set.add("Rain");
    set.add("In");
    set.add("Spain");

    Iterator&ltString> iterator = set.iterator();
  while (iterator.hasNext())
  {
    String text = iterator.next();
    System.out.println(text);
  }
}
Shorthand
public static void main(String[] args)
{
    Set&ltString> set = new HashSet&ltString>();
    set.add("Rain");
    set.add("In");
    set.add("Spain");

   for (String text : set)   
    {
        System.out.println(text);
    }
}


"Note that the words highlighted in red or green are absent in the right part. In fact, three lines are replaced by one:"

Longhand
Iterator&ltString> iterator = set.iterator();
while (iterator.hasNext())
{
    String text = iterator.next();
Shorthand

for (String text : set)


"This looks gorgeous. I like it much better this way."

"Let's look at the shorthand version of the examples above:"

Display elements of a Set
public static void main(String[] args)
{
    Set&ltString> set = new HashSet&ltString>();
    set.add("Rain");
    set.add("In");
    set.add("Spain");

    for (String text : set)   
    {
        System.out.println(text);
    }
}
Display elements of a List
public static void main(String[] args)
{
    List&ltString> list = new ArrayList&ltString>();
    list.add("Rain");
    list.add("In");
    list.add("Spain");

     for (String text : list)        
    {
        System.out.println(text);
    }
}
Display elements of a Map
public static void main(String[] args)
{
    Map<String, String> map = new HashMap<String, String>(); 
    map.put("first", "Rain");
    map.put("second", "In");
    map.put("third", "Spain");

    for (Map.Entry<String, String> pair : map.entrySet())
    {
        String key = pair.getKey();                      // Key
        String value = pair.getValue();                  // Value
        System.out.println(key + ":" + value);
    }
}

"Now you're talking!"

"I'm glad you liked it."

8
Task
New Java Syntax, level 8, lesson 2
Locked
Favorite board games
Favorite board games
Comments (53)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Dom Level 21, England, United Kingdom
20 August 2025
Looks like there is html in the examples whitch can make it confusing for beginners List&ltString> list = new ArrayList&ltString>(); Set&ltString> set = new HashSet&ltString>(); should be Set<String> set = new HashSet<String>(); List<String> list = new ArrayList<String>();
Krzysztof Kosała Level 21, Wejherowo, Poland
22 November 2023
ArrayList, LinkedList, Vector, Stack, HashSet, TreeSet, SortedSet, HashMap, TreeMap, SortedMap, Hashtable - are collections. List, Set, Map - are interfaces. What is different? Collections implement interfaces. Why and what do they give us? Interfaces give us methods. So, in ArrayList, LinkedList, Vector, Stack (which implement the List interface), they have the same names of methods but different implementations; they work differently.
Rebecca Zee Level 10, New York, United States
28 July 2023
What is the difference between using this code
List<String> list = new ArrayList<String>();
and using this code
ArrayList<String> list = new ArrayList<String>();
for and ArrayList?
larsintech Level 16, Switzerland Expert
31 January 2025
This is about a concept called polymorphism that will be covered in Java Core. ArrayList is a sub class from the abstract AbstractList class which internally implements the List interface
Barkha Mishra Level 8, Delhi, India
27 October 2022
I came back after a month, I was worried😞 that I must have forgotten. But Codegym has designed in such a way that you can still revise the previous learnings in the current level. Glad to be a part here!! 🥰
Yuxi Zhou Level 1, New York, United States
16 October 2021
What does "containers" refer to in the definition of the for-each statement?
AmirMasoud Level 26, Seattle, United States
20 January 2022
It means a place for holding Objects like Integers and Strings, .... but you cant add primitive data types into these containers
Jonaskinny Level 25, Redondo Beach, United States
17 February 2022
Think of it as a namespace if that makes it easier. It's like in the universe of data (your entire running system), referring to a specific piece of data (i.e. 123 Main Street, City, State, Zip, Country) by loading the Earth container first, then looking up who lives at this address. Assuming we colonize Mars and name everything the same, we could then look up who lives at that same address on Mars by loading the Mars container first, then using exactly the same code on it from that point.
Daisy Level 8, San Jose
5 June 2021
interesting!
Sinisa Level 11, Banja Luka, Bosnia and Herzegovina
6 March 2021
Coming from Python, I'm amazed about unnecessary Java code to print a dictionary. In Python you'd simply do: dict={"something":"nothing"} print(dict) Voila.
P.B.Kalyan Krishna Level 22, Guntur, India
13 April 2021
Why did you decide to shift from Python to Java?
Jonaskinny Level 25, Redondo Beach, United States
17 February 2022
My teenage son is starting with Python, very easy syntax indeed, yet java's verbosity lends itself better to control from the get-go. This distinction reminds me of Cold Fushion back in the day (written in java to make the api easier). You could go from Java to Cold Fushion really easily, but the other way around was more difficult. Python is also interpreted (more so than Java byte code is), so there are benefits to java imo.
Joe M Level 47, Owings Mills, United States
23 November 2020
I have only used "for-each". This is really helpful!
Asım Keskin Level 8, Ankara, Turkey
18 July 2020
Examples require defining a set with: HashSet<...> x = new HashSet... However in the lesson it never does this (the Hash in the very beginning is omitted)!?
Mateusz Level 29, Poland
27 August 2020
You can omit it because a HashSet is a child class of a Set class. This is called inheritance. Anyway, I agree that it is confusing. Hope it will be explained later in detail.
Jonaskinny Level 25, Redondo Beach, United States
17 February 2022
Declaring the variable as the interface (Set vs. HashSet) lets you switch out the implementation without changing any other code - as long as your calls on the variable only use methods contained in the declared interface. so List<String> list = new ArrayList<String>(); can later be updated to ... List<String> list = new MyFancyArrayListSubclass<String>(); You just need to only call methods common between List and MyFancyArrayListSubclass. Since you already wrote all the code using List in most of these cases, you automatically know you can just switch out the one line to use MyFancyArrayListSubclass, and nothing else needs to change.
Nikitata Level 22, Ba Sing Se, United States
8 July 2020
wow! that was a long but worthwhile lesson