Showing posts with label Java Map. Show all posts
Showing posts with label Java Map. Show all posts

Tuesday, 7 July 2015

Java : Collection Framework : Collections(newSetFromMap)

Enjoying this Java & Collections tutorial?

Subscribe to Ram N Java on YouTube

Introduction

In the Java Collections Framework, most standard Set implementations are backed by underlying Map instances (for instance, HashSet is backed internally by a HashMap). But what if you need a specialized set backed by custom map types such as a WeakHashMap or ConcurrentHashMap?

The utility method Collections.newSetFromMap(Map<E, Boolean> map) allows you to create a customized, dynamic Set backed directly by any specified empty map.

1. Understanding Collections.newSetFromMap()

The Collections.newSetFromMap() method requires that the passed map:

  • Must be completely empty at the time it is passed, otherwise an IllegalArgumentException is thrown.
  • Must accept Boolean values as its map value type (i.e., Map<E, Boolean>).
  • Should not be accessed directly once wrapped, to guarantee set integrity and avoid inconsistencies.

2. Java Code Example

Here is an example demonstrating how to wrap a WeakHashMap or HashMap into a Set using Collections.newSetFromMap():

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

public class NewSetFromMapDemo {
    public static void main(String[] args) {
        // Create an empty Map with Boolean values
        Map<String, Boolean> map = new HashMap<>();

        // Obtain a Set backed by the map
        Set<String> set = Collections.newSetFromMap(map);

        // Add elements to the Set
        set.add("Java");
        set.add("Spring");
        set.add("Hibernate");
        set.add("Java"); // Duplicate entry, will be ignored

        System.out.println("Set elements: " + set);
        System.out.println("Underlying map elements: " + map);
    }
}
  

3. Common Use Cases

  • WeakHashSet: Create a memory-sensitive Set backed by a WeakHashMap whose elements can be garbage collected when no longer strongly referenced.
  • IdentityHashSet: Create an identity-based Set backed by an IdentityHashMap using reference-equality (==) instead of equals().

Watch More Java Tutorials

Tutorials