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.