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

Java Collections · Intermediate · question 33 of 100

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

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

In Java Collections, Map and Collection are two different interfaces that serve different purposes.

Collection is an interface that represents a group of objects known as elements. It is used to store and manipulate a group of objects as a single unit. The most common sub-interfaces of Collection are List, Set, and Queue. List maintains an ordered sequence of elements, Set maintains a collection of unique elements, and Queue is a collection of elements that can be ordered in a specific way.

Map, on the other hand, is an interface that represents a mapping between a key and a value. It is used to store and manipulate key-value pairs as a single unit. The most commonly used implementation of Map is HashMap, which provides constant-time performance for basic operations such as get() and put(). Other implementations include TreeMap, LinkedHashMap, and ConcurrentHashMap.

Here is an example code that demonstrates the difference between Map and 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) {
        // Example of a Collection (List)
        List<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");
    
        // Example of a Map (HashMap)
        Map<String, Integer> map = new HashMap<>();
        map.put("One", 1);
        map.put("Two", 2);
        map.put("Three", 3);
    
        // Print the Collection and the Map
        System.out.println("Collection: " + list);
        System.out.println("Map: " + map);
    }
}

In this example, we create a List of three strings and a Map that maps three strings to three integers. We then print both the List and the Map to the console. The output looks like this:

Collection: [A, B, C]
Map: {One=1, Two=2, Three=3}

As you can see, the List is a collection of strings, while the Map is a mapping between strings and integers.

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