Home  >  Core Java

Collections.emptyMap and Collections.emptySet in Java

By Arvind Rai, May 26, 2013
In java, Collections.emptyMap is used to get empty and immutable Map . Collections.emptySet is used to get empty and immutable Set . As these are immutable so we cannot add element in the obtained Map and Set. The use of empty map and set are that if our method is returning empty map or set, so returning immutable empty map and set ensures that they cannot be changed later. Collections.emptyMap and Collections.emptySet provides a type safe view not to add element. Its performance is faster.
CollectionsEmptyDemo.java
package com.concretepage.util;
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

Collections.emptyMap() vs new HashMap()
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us