Collections unmodifiable Map Set List in Java - Java @ Desk

Tuesday, March 18, 2014

Collections unmodifiable Map Set List in Java

Collections unmodifiable Map Set List in Java

Collections that do not support any modification operations (such as add, remove and clear) are referred to as unmodifiable.

Defining a constant file in an application is a best Java practice. We define the constants in a class or an interface so that they can be used within the application without creating multiple objects of them.

What if we need pre-defined collection or Map or a List. We can define a list variable in a constant and initialize it using Arrays.asList as shown below
public static final List strings2 = Arrays.asList("Arrays.asList");

What in case of a Map or a Set? How to define and initialize a constant Map in an interface or constant file. To achieve this, you need to use java.util.Collections class. Following are the methods
1) Collections.unmodifiableMap - To create a Map constant
2) Collections.unmodifiableList - To create a List constant
3) Collections.unmodifiableSet - To create a Set constant
4) Collections.unmodifiableCollection - To create a Collection constant
5) Collections.unmodifiableSortedMap - To create a SortedMap constant
6) Collections.unmodifiableSortedSet - To create a SortedSet constant

If any modifications is applied on any of the collection created using above methods, it throws a following exception
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.util.Collections$UnmodifiableCollection.add(Collections.java:1018)
 at FileCreate.main(FileCreate.java:5)


Below is the sample implementation interface to show how to create a constant map or set or list:

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public interface CollectionsConstants {

    public static final Map<String, String> loanInterestRates = Collections.unmodifiableMap(new HashMap<String, String>() {
        {
            put("Bank Of America", "10.0");
            put("Nomura", "9.85");
        }
    });

    public static final List<String> bankNames = Collections.unmodifiableList(new ArrayList<String>() {
        {
            add("Insurance");
            add("Treatment");
            add("Loans");
            add("Attorney");
            add("Mortgage");
            add("Hosting");
            add("Rehab");
            add("Classes");
            add("Transfer");
            add("Recovery");
            add("Software");
            add("Claim");
            add("Trading");
            add("Lawyer");
            add("Donate");
            add("Credit");
            add("Degree");
        }
    });

    public static final Set<String> insuranceSet = Collections.unmodifiableSet(new HashSet<String>() {
        {
            add("Insurance");
        }
    });
    
}






No comments:

Post a Comment