List of all collections

List of all collections - 1

"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<String> set = new HashSet<String>();
    set.add("Rain");
    set.add("In");
    set.add("Spain");

     // Get an iterator for the set
     Iterator<String> 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);
    }
}
2
Task
Java Syntax,  level 8lesson 2
Locked
Code entry
Sometimes you don't need to think, you just need to hammer it out! As paradoxical as it may seem, sometimes your fingers will "remember" better than your conscious mind. That's why while training at the secret CodeGym center you will sometimes encounter tasks that require you to enter code. By entering code, you get used to the syntax and earn a little dark matter. What's more, you combat laziness.
Display elements of a List
public static void main(String[] args)
{
    List<String> list = new ArrayList<String>();
    list.add("Rain");
    list.add("In");
    list.add("Spain");

    Iterator<String> 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<String> set = new HashSet<String>();
    set.add("Rain");
    set.add("In");
    set.add("Spain");

    Iterator<String> iterator = set.iterator();
  while (iterator.hasNext())
  {
    String text = iterator.next();
    System.out.println(text);
  }
}
Shorthand
public static void main(String[] args)
{
    Set<String> set = new HashSet<String>();
    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<String> 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<String> set = new HashSet<String>();
    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<String> list = new ArrayList<String>();
    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."

Comments (43)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Daisy
Level 8 , San Jose
5 June, 13:03
interesting!
Sinisa
Level 11 , Banja Luka, Bosnia and Herzegovina
6 March, 17:35
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 11 , Guntur, India
13 April, 09:34
Why did you decide to shift from Python to Java?
Joe M
Level 11 , East Coast, United States
23 November 2020, 07:58
I have only used "for-each". This is really helpful!
Asım Keskin
Level 8 , Ankara, Turkey
18 July 2020, 09:50
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, 07:38
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.
Nikitata
Level 22 , Ba Sing Se, United States
8 July 2020, 18:43
wow! that was a long but worthwhile lesson
Madhu
Level 10 , Chennai, India
2 June 2020, 12:23
Now it all makes sense!!. I've been using the short version (for-each) without knowing where it came from.
Nickolas Johnson
Level 8 , St. Louis, United States of America
4 April 2020, 16:09
I don't think they touched on it here but if you're using a hashmap the first value (the key) has to be unique. For example, if you create a Hashmap of type <Boolean, String> you can only have two values because a Boolean type only stores one of two values.
Map<String, Boolean> map = new HashMap<String, Boolean>();
map.put("Rain", true);
map.put("In", true);
map.put("Spain", true);
map.put("Spain", false);
map.put("Rain", false);
If the above is iterated through it will return: Rain:false In:true Spain:false
Andrei
Level 33
2 November 2020, 10:49
So why does it return the opposite value when they are itterated?
Nickolas Johnson
Level 8 , St. Louis, United States of America
30 November 2020, 15:25
It's not returning the opposite value for Rain. On line 6 Rain is set to false. The code I wrote above is to show you that even though you technically "put" 5 things in, there are only 3 values in the hashmap because "Rain" is a key and key's cannot be repeated in HashMaps So this is how the code goes through: 1) sets "Rain" to true 2) sets "In" to true 3) sets "Spain" to true 4) resets "Spain" to false 5) resets "Rain" to false
Andrei
Level 33
30 November 2020, 20:30
Yes, now it makes sense. I had not yet understood the concept of map at the moment I posted that comment. :) Thanks.
Austeja
Level 10 , Kaunas, Lithuania
14 February 2020, 12:08
Guys, have you noticed that with every task there are fewer and fewer people who did it? At level 3 or 4, at the verification, I remember >3000 people who did the task before me. Now, at level 8, the last task showed only 1921. I wonder how many reach level >30?
Seb
Level 41 , Crefeld, Germany
19 February 2020, 12:44
As of today, there are probably not more than around 100 people above level 30. A few tasks only having been completed by less than 10 students... :-P The quests and tasks really are created in an excellent way - all building up upon the previous lessons and foundations. It definitely takes time to go through the tasks and lessons, but it certainly is worth the effort. There's a lot of good material and there are especially quite a number of small real-world projects and tasks starting at level 20. Hope to see you and many more on the higher levels soon. Keep it up. ;-)
Austeja
Level 10 , Kaunas, Lithuania
29 February 2020, 12:00
Thanks! I am slowly crawling upwards.
Seb
Level 41 , Crefeld, Germany
29 February 2020, 12:37
Ah, no worries - slow and steady is good. :-)
Austeja
Level 10 , Kaunas, Lithuania
29 February 2020, 12:45
<3
Gellert Varga
Level 18 , Szekesfehervar, Hungary
30 April 2020, 19:03
1) In this link: https://codegym.cc/groups/posts/20-deleting-an-element-from-an-arraylist we can learn this: "The Iterator class is responsible for safely iterating over the list of elements. It is quite simple, since it HAS ONLY 3 methods: hasNext() - returns true or false next() - returns the next item in the list remove() - removes an item from the list" 2) In the lesson above (level08.lecture02), they says this: "First, we get a special object, an iterator, from the collection. The iterator HAS ONLY TWO methods: next() and hasNext() . So, maybe is this an other iterator?... Or: which statement is false?:)
Daniel
Level 8 , Vienna, Austria
10 June 2020, 21:56
2 methods regarding next element.
Agent Smith
Level 38
15 August 2020, 20:28
I remember seeing "8,000+ people completed this task" on level 2 or 3.
Horatiu
Level 11 , Deva, Romania
2 September 2020, 13:27
yes , I saw also that the number of person that completed a task is decreasing as I advance. I am also quite slow, but since I do this as a hobby in my free time , after work, I am happy with my progress . Slow and steady is good for me
7 February 2020, 06:04
It become scary !!!
YSS
Level 16 , New York City, United States
5 December 2019, 12:13
This text is wrong it says `1. The next() method returns the next element in the collection.` it does not, it returns the current element and moves on to the next one. Later in the text again the same mistake: `"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?"`