Difference between List set and map java

Difference between List set and map java

1. Lists

Lists in Java represent an ordered collection of elements where each element has a specific index. Lists allow duplicate elements and maintain the insertion order. You can access elements in a list by their index.

2. Sets

Sets in Java represent a collection of unique elements. Unlike lists, sets do not allow duplicate elements. Sets do not maintain any specific order of elements List set and map java.

3. Maps:

Maps in Java represent a collection of key-value pairs. Each key in a map must be unique, and it is associated with exactly one value. Maps do not maintain any specific order of key-value pairs.

Now, let’s provide Java code List set and map java examples to illustrate these concepts:

List set and map java

Example
Lists Example:
java
import java.util.ArrayList;
import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        // Creating a list
        List<String> myList = new ArrayList<>();

        // Adding elements to the list
        myList.add("Apple");
        myList.add("Banana");
        myList.add("Orange");
        
        // Accessing elements by index
        System.out.println("Element at index 1: " + myList.get(1));

        // Iterating through the list
        System.out.println("List elements:");
        for (String fruit : myList) {
            System.out.println(fruit);
        }
    }
}

Example

Sets Example:
java
import java.util.HashSet;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        // Creating a set
        Set<String> mySet = new HashSet<>();

        // Adding elements to the set
        mySet.add("Apple");
        mySet.add("Banana");
        mySet.add("Orange");
        mySet.add("Apple"); // Duplicate element, will be ignored
        
        // Iterating through the set
        System.out.println("Set elements:");
        for (String fruit : mySet) {
            System.out.println(fruit);
        }
    }
}


Example
Maps Example:
java
import java.util.HashMap;
import java.util.Map;

public class MapExample {
    public static void main(String[] args) {
        // Creating a map
        Map<Integer, String> myMap = new HashMap<>();

        // Adding key-value pairs to the map
        myMap.put(1, "Apple");
        myMap.put(2, "Banana");
        myMap.put(3, "Orange");
        
        // Accessing value by key
        System.out.println("Value associated with key 2: " + myMap.get(2));

        // Iterating through the map
        System.out.println("Map elements:");
        for (Map.Entry<Integer, String> entry : myMap.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}

Homepage

Readmore