Home » Java programming language

Java Collections newSetFromMap() Method with Example

Collections Class newSetFromMap() method: Here, we are going to learn about the newSetFromMap() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on February 04, 2020

Collections Class newSetFromMap() method

  • newSetFromMap() method is available in java.util package.
  • newSetFromMap() method is used to return a set backed by the given map (m).
  • newSetFromMap() method is a static method, so it is accessible with the class name and if we try to access the method with the class object then we will not get an error.
  • newSetFromMap() Method may throw an exception at the time of returning set from the given map.
    IllegalArgumentException: This exception may throw when the given parameter map(m) is not "blank".

Syntax:

    public static Set newSetFromMap(Map m);

Parameter(s):

  • Map m – represents the backing map.

Return value:

The return type of this method is Set, it returns the set backed by the given map(m).

Example:

// Java program is to demonstrate the example of
// newSetFromMap(Map m) method of Collections

import java.util.*;

public class NewSetFromMapOfCollections {
    public static void main(String args[]) {
        // Creating a HashMap object
        Map < Integer, Boolean > m = new HashMap < Integer, Boolean > ();

        // Here, we are creating set object
        // from the given map object
        Set < Integer > s = Collections.newSetFromMap(m);

        // By using add()method is to add
        // objects in a set object
        s.add(10);
        s.add(20);
        s.add(30);
        s.add(40);
        s.add(50);

        // Display values of set and map
        System.out.println("Map is: " + s);
        System.out.println("Set is: " + m);
    }
}

Output

Map is: [50, 20, 40, 10, 30]
Set is: {50=true, 20=true, 40=true, 10=true, 30=true}






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.