WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Basic · question 9 of 100

What is the difference between a Map and a Collection in Java?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

In Java, both Map and Collection are interfaces in the Java Collections Framework that represent a group of related elements, but they have some key differences.

Structure: A Collection represents an unordered group of related elements, while a Map represents a group of related elements that are stored as key-value pairs.

Duplication of elements: A Collection may contain duplicate elements, while a Map cannot contain duplicate keys (though it can contain duplicate values).

Accessing elements: In a Collection, elements are accessed using an index or an iterator. In a Map, elements are accessed using a key.

Here’s an example of how to use a Map and a Collection in Java:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Example {
    public static void main(String[] args) {
        // create a list
        List<String> myList = new ArrayList<>();
        myList.add("apple");
        myList.add("banana");
        myList.add("orange");
        
        // create a map
        Map<String, Integer> myMap = new HashMap<>();
        myMap.put("apple", 1);
        myMap.put("banana", 2);
        myMap.put("orange", 3);
        
        // access an element in the list
        String element1 = myList.get(1);
        System.out.println("Element at index 1 of list: " + element1);
        
        // access an element in the map
        int element2 = myMap.get("banana");
        System.out.println("Value associated with key 'banana' in map: " + element2);
    }
}

In this example, we create a List called "myList" using the ArrayList class, and add some strings to it using the "add" method. We then create a Map called "myMap" using the HashMap class, and add some key-value pairs to it using the "put" method. We then access an element at index 1 of the List using the "get" method, and print out the result. We also access an element in the Map using the key "banana" and the "get" method, and print out the result.

The output of this program would be:

Element at index 1 of list: banana
Value associated with key 'banana' in map: 2

As you can see, the List is accessed using an index, while the Map is accessed using a key.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics