Home page

Showing posts with label Collection. Show all posts
Showing posts with label Collection. Show all posts

Monday, June 19, 2023

TreeMap in JAVA

In Java, TreeMap is a class that implements the SortedMap interface and provides a red-black tree-based implementation of a NavigableMap. It stores key-value pairs in a sorted order based on the natural ordering of the keys or a custom comparator. Here's when and why you would use a TreeMap:

Sorted and ordered data: If you need to maintain the elements in a sorted order based on the keys, TreeMap is a suitable choice. It automatically sorts the keys, allowing efficient retrieval of entries in a specific order.

Range operations: TreeMap provides methods to perform range operations, such as getting a sub-map of keys within a specific range or finding the nearest key greater or less than a given key.

Custom sorting: TreeMap allows you to define a custom comparator to sort the keys in a specific order. This can be useful when the natural ordering of the keys is not desirable.

Here's an example of how to use TreeMap in Java: 

import java.util.TreeMap;

public class TreeMapExample {

    public static void main(String[] args) {

        // Create a TreeMap

        TreeMap<Integer, String> treeMap = new TreeMap<>();

        // Add key-value pairs to the TreeMap

        treeMap.put(3, "Apple");

        treeMap.put(1, "Banana");

        treeMap.put(2, "Orange");

        // Iterate over the TreeMap entries

        for (var entry : treeMap.entrySet()) {

            System.out.println(entry.getKey() + " -> " + entry.getValue());

        }

        // Get the first and last keys

        int firstKey = treeMap.firstKey();

        int lastKey = treeMap.lastKey();

        System.out.println("First key: " + firstKey); // Output: 1

        System.out.println("Last key: " + lastKey); // Output: 3

        // Get a sub-map of keys within a range

        TreeMap<Integer, String> subMap = treeMap.subMap(1, 3);

        System.out.println("Sub-map: " + subMap); // Output: {1=Banana, 2=Orange}

        // Get the nearest key greater or less than a given key

        int greaterKey = treeMap.higherKey(2);

        int lowerKey = treeMap.lowerKey(2);

        System.out.println("Greater key: " + greaterKey); // Output: 3

        System.out.println("Lower key: " + lowerKey); // Output: 1

    }

}

In this example, we create a TreeMap called treeMap that maps Integer keys to String values.

We add key-value pairs to the TreeMap using the put() method.

We iterate over the TreeMap entries using a for-each loop and print the keys and values.

We retrieve the first and last keys using the firstKey() and lastKey() methods.

We get a sub-map of keys within a range using the subMap() method.

We find the nearest key greater and less than a given key using the higherKey() and lowerKey() methods.

Output:
1 -> Banana
2 -> Orange
3 -> Apple
First key: 1
Last key: 3
Sub-map: {1=Banana, 2=Orange}
Greater key: 3
Lower key: 1

As shown in the example, TreeMap allows you to store key-value pairs in a sorted order. It provides methods to retrieve entries in a specific order, perform range operations, and find nearest keys

Wednesday, June 14, 2023

HashSet in JAVA

A HashSet in Java is a data structure that represents an unordered collection of unique elements. It is implemented using a hash table, which provides constant-time complexity for the basic operations (add, remove, contains), assuming a good hash function.

You can use a HashSet in situations where you need to store a collection of unique elements and order is not important. Some common use cases for HashSet include:

Removing duplicates: If you have a collection of elements where you want to eliminate duplicate entries, a HashSet can be used. It ensures that each element is unique in the set.

Efficient membership testing: If you frequently need to check whether an element is present in a collection, a HashSet can provide fast membership testing due to its hashing-based implementation.

Here's an example of how you can use a HashSet in Java:

import java.util.HashSet;

public class HashSetExample {

    public static void main(String[] args) {

        HashSet<String> set = new HashSet<>();

        // Adding elements to the HashSet

        set.add("Apple");

        set.add("Banana");

        set.add("Orange");

        set.add("Apple"); // Duplicate entry, will be ignored

        // Iterating over the elements in the HashSet

        for (String element : set) {

            System.out.println(element);

        }

        // Checking if an element exists in the HashSet

        boolean containsBanana = set.contains("Banana");

        System.out.println("Contains Banana? " + containsBanana);

        // Removing an element from the HashSet

        boolean removed = set.remove("Orange");

        System.out.println("Removed Orange? " + removed);

        // Size of the HashSet

        System.out.println("Size of HashSet: " + set.size());

    }

}

In this example, we create a HashSet called set to store strings.

We add elements to the set using the add() method. Note that the duplicate entry of "Apple" is ignored, as HashSet does not allow duplicate elements.

We iterate over the elements of the set using a for-each loop and print each element.

We check if an element exists in the set using the contains() method.

We remove an element from the set using the remove() method and store the result in a boolean variable.

Finally, we print the size of the set using the size() method.

Output:
Apple
Banana
Orange
Contains Banana? true
Removed Orange? true
Size of HashSet: 2

Tuesday, June 13, 2023

LinkedHashSet in JAVA

A LinkedHashSet in Java is a data structure that combines the features of both a HashSet and a LinkedList. It maintains a linked list of the entries in the set, which allows for predictable iteration order, while also providing constant-time complexity for the basic operations (add, remove, contains).

You can use a LinkedHashSet in situations where you need to maintain the order of insertion of elements, along with the uniqueness of elements. Some common use cases for LinkedHashSet include:

Preserving insertion order: If you need to iterate over the elements of a set in the order they were inserted, a LinkedHashSet can be used.

Removing duplicates while preserving order: If you have a collection of elements where duplicates need to be eliminated but the order of the remaining elements must be maintained, a LinkedHashSet can be used.

Here's an example of how you can use a LinkedHashSet in Java:

import java.util.LinkedHashSet;

public class LinkedHashSetExample {

    public static void main(String[] args) {

        LinkedHashSet<String> set = new LinkedHashSet<>();

        // Adding elements to the LinkedHashSet

        set.add("Apple");

        set.add("Banana");

        set.add("Orange");

        set.add("Apple"); // Duplicate entry, will be ignored

        // Iterating over the elements in the LinkedHashSet

        for (String element : set) {

            System.out.println(element);

        }

        // Checking if an element exists in the LinkedHashSet

        boolean containsBanana = set.contains("Banana");

        System.out.println("Contains Banana? " + containsBanana);

        // Removing an element from the LinkedHashSet

        boolean removed = set.remove("Orange");

        System.out.println("Removed Orange? " + removed);

        // Size of the LinkedHashSet

        System.out.println("Size of LinkedHashSet: " + set.size());

    }

}

In this example, we create a LinkedHashSet called set to store strings.

We add elements to the set using the add() method. Note that the duplicate entry of "Apple" is ignored, as LinkedHashSet does not allow duplicate elements.

We iterate over the elements of the set using a for-each loop and print each element.

We check if an element exists in the set using the contains() method.

We remove an element from the set using the remove() method and store the result in a boolean variable.

Finally, we print the size of the set using the size() method.

Output:
Apple
Banana
Orange
Contains Banana? true
Removed Orange? true
Size of LinkedHashSet: 2