Collection interface – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 23 Jul 2023 08:36:42 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Collection interface – Programmerbay https://programmerbay.com 32 32 Map Interface in Java With Program Example https://programmerbay.com/map-interface-in-java-with-program-example/ https://programmerbay.com/map-interface-in-java-with-program-example/#respond Sun, 23 Jul 2023 08:36:42 +0000 https://programmerbay.com/?p=9490 The Map interface is part of Collection framework, however, it is not a sub-interface of the collection. It deals with and represents a group of objects in key-value pair. In this, keys and values are objects where keys must be unique and values can be duplicated. Each key-value pair is termed as Entry and a set of such entries is known as Map.

Collection Framework

It can be defined as an interface that empowers to store and fetch elements based on a key where a key can not be duplicated and can refer to at most a single value.
Map interface consists its various methods to operate with data. There are more often used methods such as put() method to add an element in a key-value pair, get() method to fetch data based on a key and, remove() method to remove an element.

Point to Remember

1) A map represents data structure that stores data in key-value pair
2) It doesn’t allow duplicate key
3) A key can only be associated to at most single value
4) It accepts null key. Only TreeMap implementation doesn’t allow null

How to create a Map Object?

Map is an interface and its implementation classes can be used to create its object. In below example, we’ve used HashMap.

Map<K,V> map = new HashMap<>();

Method of Maps

MethodExplanation
put(key,value)It adds elements in key value form where key represents identifier and value is the actual data. If one tries to make a duplicate entry, then the old value will be replaced with new one. And returns old data, otherwise null will be returned.
putAll(Map Obj)It adds all the given map data to the calling Map with the same key-value mapping
clear()It clears the map and removes all the enteries
containsKey(key)It check whether the given key present in the map or not, if yes , it would return true otherwise false
containsValue( value)It returns true, if the given value is present with one or more key mappings
entrySet()It returns a Set object representing key-value elements
forEach(action)It enables to iterate key-value enteries one by one until all the enteries iterated
get(key)It returns value associated with the provided key
getOrDefault( key, defaultValue)It returns value associated with the provided key, if it's not present, the provided default value would be returned
isEmpty()It checks whether the given map is empty or not
keySet()It is used to get list of keys present in the map
putIfAbsent(key, value)It adds an element if the given key is not associated with any value in the map and returns null, otherwise existing key value
remove(key)It removes a key-value mapped with the given key
remove( key, value)It removes an entry, provided with the given associated key mapped with the given value only
replace(key, value)It replaces the existing mapping if the given key having a mapping in a map
replace(key, oldValue, newValue)It replaces the existing mapping with the mentioned key, if the targeted key having the old value mapped to it
size()It returns the size of enteries in a map
values()It returns collection object containing all the values in a map

Java Program to demonstrate the basic operations of Map interface

Program:

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

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

        // putting enteries in the map
        map.put("p","programmerbay");
        map.put("e","Example");
        map.put("a","Another");

        // Retrieving an element based on a key
        System.out.println("fetching value associated with p "+map.get("p"));


        // Iterating over Map elements

        Set<Map.Entry<String,String>> enteries = map.entrySet();

        for (Map.Entry<String,String> singleEntry:
             enteries) {
            System.out.println(singleEntry);
        }
    }
}

Output:

fetching value associated with p programmerbay
p=programmerbay
a=Another
e=Example

Implementing Classes and Interfaces of Map

There are various implementation classes and sub interfaces of Map interface.

Below are the following sub interfaces:

1) SortedMap

SortedMap is a sub interface of Map that provides a way to specify ordering on its keys. By default, keys are sorted in natural order. Further, with the help of Comparator, one can also specify custom sorting order. Additionally, keys inserted must implement Comparable interface.

2) NevigableMap

NavigableMap extends SortedMap that provides navigation methods to navigate through entries of a Map. Methods like lowerEntry, ceilingEntry, lowerKey, floorKey and higherKey are used for locating entries in a map.

Similar to NavigableSet, NavigableMap can also be traversed in both ascending or descending key order. However, if one considers performance, then ascending operations are faster than descending ones.

Below are the following implementation classes:

1) HashMap

HashMap provides a hash table based implementation to store data in key-value pair. It accepts a single null key and multiple null values. It doesn’t guarantee the order of a map. It uses a hash function to calculate the hash code, based on which the respective element get stored among the buckets. As a result, it serves constant-time performance for operations like adding and fetching data.

2) LinkedHashMap

LinkedHashMap is a subclass of HashMap that represents Hash table and linked list as its underlying data structure. It preserves the order of entries which is maintained and defined by a doubly linked list. In other words, it fetches elements in the same order in which they are previously added. It permits at most one null key.

3) IdentityHashMap

IdentityHashMap is an implementation class of Map interface that uses Hash Table as its underlying data structure. Unlike HashMap, it uses == operator to identify duplicate entries.

4) WeakHashMap

WeakHashMap is a Hash table based implementation where entries get automatically cleaned up by garbage collector when its key reference for a mapped value is no longer exist or in use.

5) TreeMap

TreeMap is a red-black tree based implementation class of Map interface. It stores elements in some specific order of its key. It doesn’t allow null key.

Basic Operations in Map

There are various operations that can be performed on data. Below are some frequently used operations.
1) Adding elements
2) Updating elements
3) Removing elements
4) Iterating over elements
5) Retrieving element

1) Adding elements

put() and putIfAbsent() method can be used to add element in a map. Both methods are used in different situations
put(k,v) : It adds single element to a given map. It returns null, indicating that no key mapping is exist
putAll(Map obj) : It adds all the elements consisting in passed Map Object.
putIfAbsent(k,v) : It is similar to put() method but only adds elements if the given key mapping is not present in the targeted map

Program:

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

public class MapExample {
public static void main(String[] args) {
// Creating a Map object
Map<String,String> map = new HashMap<>();
// putting entries in the map
map.put("p","programmerbay");

// Printing Map elements
System.out.println(map);


Map<String,String> differentMap = new HashMap<>();
differentMap.put("e","example");

// Adding element to Map elements
map.putAll(differentMap);

// Printing Map elements
System.out.println(map);

// putIfAbsent is used to add element
map.putIfAbsent("c","code ");

// Printing Map elements
System.out.println(map);

}
}

Output:

{p=programmerbay}
{p=programmerbay, e=example}
{p=programmerbay, c=code , e=example}

2) Updating elements

put() is also used to update the existing key mapping in a map. It returns old key-value existing mapping if present in the map, otherwise, null. In other words, put() replaces an entry if passed key already is present, otherwise, add-operation is performed.

Program:

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

public class MapExample {
public static void main(String[] args) {
// Creating a Map object
Map<String,String> map = new HashMap<>();
// putting entries in the map
map.put("p","programmerbay");

System.out.println(map);

// updating existing key
map.put("p","updated");

System.out.println(map);

}
}

Output:

{p=programmerbay}
{p=updated}

3) Removing elements

remove() method is used to delete a key value pair from a map. There are various overloaded methods of remove.
remove(k) : It removes a key-value mapped with given key in a map
remove(k,v) : It removes a key-value pair present that matches with provided key and value.

Program:

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

public class MapExample {
public static void main(String[] args) {
// Creating a Map object
Map<String,String> map = new HashMap<>();
// putting entries in the map
map.put("p","programmerbay");

System.out.println(map);

// remove existing key
map.remove("p","programmerbay");

System.out.println(map);

}
}

Output:

{p=programmerbay}
{}

4) Iterating over elements

Enhanced forEach() can be used to iterate over elements. In order to iterate through a map, first one needs to get its all entries using entrySet() method.

Program:

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

public class MapExample {
    public static void main(String[] args) {
        // Creating a Map object
        Map<String,String> map  = new HashMap<>();
        // putting entries in the map
        map.put("p","programmerbay");
        map.put("c","code");
        map.put("e","example");



        Set<Map.Entry<String,String>> enteries = map.entrySet();

        for (Map.Entry<String,String> singleEntry:
             enteries) {
            System.out.println(singleEntry);
        }
    }
}

Output:

p=programmerbay
c=code
e=example

 

5) Retrieving element

get() method is used to retrieve value associated with a key. It accepts key name based on which the associated value is retrieved.

Program:

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

public class MapExample {
    public static void main(String[] args) {
        // Creating a Map object
        Map<String,String> map  = new HashMap<>();
        // putting entries in the map
        map.put("p","programmerbay");

        System.out.println(map);

        // diplaying value based on key
        System.out.println(map.get("p"));

    }
}

Output:

{p=programmerbay}
programmerbay

 

 

 

]]>
https://programmerbay.com/map-interface-in-java-with-program-example/feed/ 0
HashSet Class in Java With Program Example https://programmerbay.com/hashset-class-in-java-with-program-example/ https://programmerbay.com/hashset-class-in-java-with-program-example/#respond Thu, 13 Jul 2023 17:43:58 +0000 https://programmerbay.com/?p=9366 Set interface doesn’t provide any additional method, as a result, implementation classes use only collection interface methods.
HashSet is an implementing class of Set interface and it represents Hash Table as its underlying data structure. It is a collection of unordered unique elements that don’t allow duplicates. It also doesn’t preserve insertion order as it uses hash code to store an element. Meaning, the elements are stored based on some hash values and can be retrieved in any order.

Screenshot from 2023 07 10 23 23 20

It uses several methods of Collection interface i.e. add(), remove(), contains(). The add() method returns false and doesn’t add an element if one tries to insert a duplicate element. The advantage of using HashSet, it makes searching faster.

It can store different types of objects and allows at most a single null value to hashSet.
It also implements the Serializable and Collneable interface.

Set is the best choice when the frequent search operation is required.

Syntax:

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

Point to Remember :

  1. It doesn’t preserve insertion order
  2. It allows atmost single null value
  3. It can store various type of objects at the same time
  4. It uses hash table as its underlying data structure
  5. It is a best choice when frequent search operation is involved
  6. It doesn’t allow duplicate that makes it ideal for storing unique elements

 

Constructors of HashSet

There are 4 constructors in HashSet:

1) HashSet()

It is a default constructor that creates an empty Set with a default capacity of 16 elements and having default fill ratio 0.75.

HashSet<T> obj = new HashSet<>() :

Fill ratio/ Load Factor : It simply means after which ratio/ percentage, a new set should be created. For instance, if fill ratio is 0.75, then a new hashSet would be created after occupying 75% capacity of the set.

2) HashSet(int initialCapacity)

It creates an empty set with the provided initial capacity value with default fill ratio 0.75.

HashSet<T> h = new HashSet<>(int initialCapacity);

3) HashSet<T>(int initialCapacity, float loadFactor)

It creates an empty set with provided initial capacity and load factor.

HashSet<T> h = new HashSet<T>(int initialCapacity, float loadFactor);

4) HashSet<T>(Collection obj)

It creates a set with the collection elements passed in the constructor. It can be arrayList, linkedList or any other object that implements collection interface.

HashSet<T> h = new HashSet<T>(Collection obj);

Program to demonstrate creation of HashSet in Java

import java.util.*;

public class SetExample {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>() ;  // Creating set object
        set.add("Programmerbay");
        set.add("Example");
        set.add("Duplicate");
        set.add("Duplicate");
        System.out.println(set);
    }
}

Output:

[Example, Duplicate, Programmerbay]

 

How HashSet or HashMap works in Java?

HashSet internally uses the HashMap constructor to create an empty set with a default capacity of 16 and 0.75 load factor.
When the add() method is called, again put() method of HashMap is also invoked where the element that is being added acts as a key and a constant value (PRESENT) acts as a value. When one tries to add the same element then, we all know, what would happen when one tries to add an element with the same key in a map, it would override or replace the existing key-value pair. That is why HashSet doesn’t allow duplicate elements.

Further, lets see the working of HashMap.

HashMap also adheres HashTable Alogrithm Internally.

When a HashMap object is created, JVM creates Hash Table which is nothing but an array of nodes or buckets internally concerning the capacity of the Set or Map. These buckets act as a node that connects like a linked list.
When an element is added or put in the object, a corresponding hashcode or hash is generated using hashCode() method.

Based on the Modular operator it identifies the index and stores the data in that bucket (consisting array of nodes) residing on that position.
If two elements are having same hashcode, then it would not directly be stored in the same bucket, instead, the equal() method will be used to check whether the two elements are the same or not. If both are evaluated as different, then it would be stored in the same bucket otherwise, it will be replaced.

The situation of having the same hash of two elements is also known as Hashing collision, to deal with it, the equals() method is internally used by JVM.

Methods in HashSet

Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

]]>
https://programmerbay.com/hashset-class-in-java-with-program-example/feed/ 0