Main differences between a Set and a Map in Java are:
1. Duplicate Elements: A Set does not allow inserting
duplicate elements. A Map does not allow using duplicate
keys, but it allows inserting duplicate values for unique
keys.
2. Null values: A Set allows inserting maximum one null
value. In a Map we can have single null key at most and
any number of null values.
3. Ordering: A Set does not maintain any order of elements.
Some of sub-classes of a Set can sort the elements in an
order like LinkedHashSet. A Map does not maintain any
order of its elements. Some of its sub-classes like
TreeMap store elements of the map in ascending order of
keys.
xxxxxxxxxx
public class MapExample {
public static void main(String[] args)
{
// Creating an empty Linked Hash Map
LinkedHashMap<Integer, String> students = new LinkedHashMap<>();
// Adding data to Linked Hash Map in key-value pair
students.put(101, "Aaliyah");
students.put(102, "Taylor");
students.put(103, "Zayn");
students.put(104, "Sabrina");
students.put(105, "Paul");
// Showing size and data of the Linked Hash Map
System.out.println("The size of the Linked Hash Map is:- "+ students.size());
System.out.println(students);
// Checking whether a certaint key is available or not
if (students.containsKey(105)) {
String name = students.get(105);
System.out.println("The name of the student having Id 105 is:- " + name);
}
}
}