Sunday, June 4, 2023

Java HashMap ContainsKey and ContainsValue Example - How to check if a Key Exists in Map?

To check if a key exists in a HashMap in Java, you can use the containsKey() method. Similarly, to check if a value exists in a HashMap, you can use the containsValue() method. 

Here's an example that demonstrates both scenarios:


import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
    public static void main(String[] args) {
        // Creating a HashMap
        Map hashMap = new HashMap<>();

        // Adding key-value pairs to the HashMap
        hashMap.put("Key1", 1);
        hashMap.put("Key2", 2);
        hashMap.put("Key3", 3);

        // Checking if a key exists using containsKey()
        String keyToCheck = "Key2";
        if (hashMap.containsKey(keyToCheck)) {
            System.out.println("The key '" + keyToCheck + "' exists in the HashMap.");
        } else {
            System.out.println("The key '" + keyToCheck + "' does not exist in the HashMap.");
        }

        // Checking if a value exists using containsValue()
        int valueToCheck = 3;
        if (hashMap.containsValue(valueToCheck)) {
            System.out.println("The value " + valueToCheck + " exists in the HashMap.");
        } else {
            System.out.println("The value " + valueToCheck + " does not exist in the HashMap.");
        }
    }
}

In this example, we create a HashMap called hashMap and add three key-value pairs using the put() method. Then, we demonstrate how to check if a key exists using the containsKey() method. We specify the key to check in the keyToCheck variable. If the key exists in the HashMap, the corresponding message is printed; otherwise, a different message is printed. 

Next, we show how to check if a value exists in the HashMap using the containsValue() method. We specify the value to check in the valueToCheck variable. If the value exists in the HashMap, the corresponding message is printed; otherwise, a different message is printed. 

The output of this example will be:


The key 'Key2' exists in the HashMap.
The value 3 exists in the HashMap.

As you can see, the program correctly identifies that the key "Key2" exists in the HashMap, and the value 3 also exists in the HashMap.

How to Merge two HashMap in Java 8 - Map.merge() example Tutorial

In Java 8, you can use the merge() method provided by the Map interface to merge two HashMaps. The merge() method allows you to specify a merging function that determines how conflicting values for the same key should be resolved. 

Here's an example:


import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
    public static void main(String[] args) {
        // Creating two HashMaps
        Map map1 = new HashMap<>();
        Map map2 = new HashMap<>();

        // Adding key-value pairs to map1
        map1.put("Key1", 1);
        map1.put("Key2", 2);

        // Adding key-value pairs to map2
        map2.put("Key2", 3);
        map2.put("Key3", 4);

        System.out.println("HashMap 1: " + map1);
        System.out.println("HashMap 2: " + map2);

        // Merging the two HashMaps using merge() and resolving conflicts with sum
        map2.forEach((key, value) -> map1.merge(key, value, Integer::sum));

        System.out.println("Merged HashMap: " + map1);
    }
}

In this example, we create two HashMaps: map1 and map2. We add key-value pairs to each map using the put() method. Then, we print the contents of both HashMaps. 

To merge the two HashMaps, we use the merge() method on map1 and pass map2 as an argument. We provide a lambda expression (key, value) -> map1.merge(key, value, Integer::sum) as the merging function. This lambda expression specifies that when a conflict occurs, the values should be summed.

The merge() method takes three arguments: the key, the value from the map2, and the merging function. It merges the key-value pairs from map2 into map1, applying the merging function to resolve conflicts. If the key already exists in map1, the merging function is called with the existing value and the new value, and the result is stored as the new value for the key. If the key is not present in map1, the key-value pair from map2 is added to map1 as is. 

Finally, we print the merged HashMap, map1. 

The output of this example will be:


HashMap 1: {Key1=1, Key2=2}
HashMap 2: {Key2=3, Key3=4}
Merged HashMap: {Key1=1, Key2=5, Key3=4}

As you can see, the values for the common key "Key2" are merged according to the specified merging function, which in this case is the sum of the values. The value for "Key2" becomes 5 in the merged HashMap.

How to update value for a given key in HashMap - Java 8 getOrDefault() example

In Java 8, you can use the getOrDefault() method in conjunction with the put() method to update the value for a given key in a HashMap. 

Here's an example:


import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
    public static void main(String[] args) {
        // Creating a HashMap
        Map hashMap = new HashMap<>();

        // Adding initial key-value pairs
        hashMap.put("Key1", 1);
        hashMap.put("Key2", 2);
        hashMap.put("Key3", 3);

        System.out.println("HashMap before update: " + hashMap);

        // Updating the value for a given key using getOrDefault() and put()
        String keyToUpdate = "Key2";
        int newValue = 10;

        int oldValue = hashMap.getOrDefault(keyToUpdate, 0);
        hashMap.put(keyToUpdate, newValue);

        System.out.println("HashMap after update: " + hashMap);
    }
}

In this example, we create a HashMap called hashMap to store key-value pairs. We add three initial key-value pairs using the put() method. Then, we print the hashMap before the update. 

To update the value for a given key, we specify the key to update (keyToUpdate) and the new value (newValue). We use getOrDefault(key, defaultValue) to retrieve the current value associated with the key. If the key is present, it returns the current value; otherwise, it returns the specified default value (0 in this case). We store the old value in oldValue variable. 

Next, we use the put(key, value) method to update the value for the given key. We provide the keyToUpdate and newValue as arguments. If the key is already present in the map, the value will be updated; otherwise, a new key-value pair will be added. 

Finally, we print the updated hashMap. The output of this example will be:


HashMap before update: {Key1=1, Key2=2, Key3=3}
HashMap after update: {Key1=1, Key2=10, Key3=3}

As you can see, the value for the key "Key2" is updated from 2 to 10 in the HashMap.

How to add element at the head and tail of a LinkedList in Java? Example

To add elements at the head and tail of a LinkedList in Java, you can use the addFirst() and addLast() methods provided by the LinkedList class. 

Here's an example:



import java.util.LinkedList;

public class LinkedListExample {
    public static void main(String[] args) {
        // Creating a LinkedList
        LinkedList linkedList = new LinkedList<>();

        // Adding elements at the head using addFirst()
        linkedList.addFirst("Element 1");
        linkedList.addFirst("Element 2");
        linkedList.addFirst("Element 3");

        System.out.println("LinkedList after adding at the head: " + linkedList);

        // Adding elements at the tail using addLast()
        linkedList.addLast("Element 4");
        linkedList.addLast("Element 5");
        linkedList.addLast("Element 6");

        System.out.println("LinkedList after adding at the tail: " + linkedList);
    }
}

In this example, we create a LinkedList called linkedList. We use the addFirst() method to add elements at the head of the list. We add three elements: "Element 1", "Element 2", and "Element 3". Then, we use the addLast() method to add elements at the tail of the list. We add three more elements: "Element 4", "Element 5", and "Element 6". Finally, we print the updated LinkedList. The output of this example will be:


LinkedList after adding at the head: [Element 3, Element 2, Element 1]
LinkedList after adding at the tail: [Element 3, Element 2, Element 1, Element 4, Element 5, Element 6]


As you can see, the elements are added at the head and tail of the LinkedList as expected.

How to Union and Intersection of two Set in Java - Google Guava Example

To perform union and intersection operations on two sets in Java using Google Guava, you can utilize the Sets.union() and Sets.intersection() methods provided by the Guava library. 

Here's an example:


import com.google.common.collect.Sets;
import java.util.HashSet;
import java.util.Set;

public class SetOperationsExample {
    public static void main(String[] args) {
        // Creating two sets
        Set set1 = new HashSet<>();
        Set set2 = new HashSet<>();

        // Adding elements to set1
        set1.add(1);
        set1.add(2);
        set1.add(3);

        // Adding elements to set2
        set2.add(2);
        set2.add(3);
        set2.add(4);

        // Performing union operation using Guava's Sets.union()
        Set union = Sets.union(set1, set2);
        System.out.println("Union: " + union);

        // Performing intersection operation using Guava's Sets.intersection()
        Set intersection = Sets.intersection(set1, set2);
        System.out.println("Intersection: " + intersection);
    }
}


In this example, we create two sets set1 and set2 using the HashSet class. We add elements to both sets. Then, we use Sets.union(set1, set2) to perform the union operation and Sets.intersection(set1, set2) to perform the intersection operation. 

The results are stored in the union and intersection sets, respectively. 

Finally, we print the results. Make sure you have the Guava library added to your project's dependencies for this code to work.