Collections.emptyMap and Collections.emptySet in Java

By Arvind Rai, February 04, 2022
On this page we will learn Collections.emptyMap and Collections.emptySet methods.
Collections.emptyMap
The emptyMap method returns an immutable empty map.
Map<Integer, String> map = Collections.emptyMap(); 
Collections.emptySet
The emptySet method returns an immutable empty set.
Set<String> s = Collections.emptySet(); 

Immutable map and set cannot add or remove elements. The use of immutable empty map and set are that if our methods are returning empty map or set, so returning immutable empty map and set ensures that they cannot be changed later.

Example

CollectionsEmptyDemo.java
package com.concretepage;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

public class CollectionsEmptyDemo {
    int row = getRowFromDB();
    //immutable empty Map
    public Map<Integer,String> getDataInMap(){
    	Map<Integer,String> map = null;
    	if (row == 0) {
    		map = Collections.emptyMap();
    		return map;
    	} 
        return map;
    }
    //immutable empty Set
    public Set<String> getDataInSet(){
        Set<String> set = null;
        if (row == 0) {
        	set = Collections.emptySet();
        }
        return set;
    }
    private int getRowFromDB() {
    	int cnt = 0; //access DB to calculate rows
    	//returns DB rows
    	return cnt;
    }
} 
For the example suppose we are returning data from database and if no rows fetched then instead of returning null, we can return immutable Map or Set as required.

Reference

Java Collections
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us