VOOZH about

URL: https://www.geeksforgeeks.org/java/collections-newsetfrommap-method-in-java-with-examples/

⇱ Collections newSetFromMap() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Collections newSetFromMap() method in Java with Examples

Last Updated : 25 Oct, 2019
The newSetFromMap() method of java.util.Collections class is used to return a set backed by the specified map. The resulting set displays the same ordering, concurrency, and performance characteristics as the backing map. In essence, this factory method provides a Set implementation corresponding to any Map implementation. There is no need to use this method on a Map implementation that already has a corresponding Set implementation (such as HashMap or TreeMap). Syntax:
public static Set newSetFromMap(Map map)
Parameters: This method takes the backing map as a parameter Return Value: This method returns the set backed by the map Exception: This method throws IllegalArgumentException, if map is not empty. Below are the examples to illustrate the newSetFromMap() method Example 1:
Output:
Map is: {C=true, B=true, A=true, D=true}
Set from Map is: [C, B, A, D]
Example 2: for IllegalArgumentException
Output:
Exception thrown : java.lang.IllegalArgumentException: Map is non-empty
Comment