Sunteți pe pagina 1din 5

HashSet vs HashMap

Differences:

HASHSET HASHMAP

HashSet class implements the Set HashMap class implements the Map
interface interface
HashMap is used for storing key &
value pairs. In short it maintains the
mapping of key & value (The
In HashSet we store
HashMap class is roughly equivalent
objects(elements or values) e.g. If we
to Hashtable, except that it is
have a HashSet of string elements
unsynchronized and permits nulls.)
then it could depict a set of HashSet
This is how you could represent
elements: {“Hello”, “Hi”, “Bye”,
HashMap elements if it has integer
“Run”}
key and value of String type: e.g. {1-
>”Hello”, 2->”Hi”, 3->”Bye”, 4-
>”Run”}
HashSet does not allow duplicate HashMap does not allow duplicate
elements that means you can not keys however it allows to have
store duplicate values in HashSet. duplicate values.
HashSet permits to have a single null HashMap permits single null key and
value. any number of null values.
HashSet example
import java.util.HashSet;
class HashSetDemo{
public static void main(String[] args) {
HashSet<String> hset = new HashSet<String>();
hset.add("AA");
hset.add("BB");
hset.add("CC");
hset.add("DD");
// Displaying HashSet elements
System.out.println("HashSet contains: ");
for(String temp : hset){
System.out.println(temp); }
}}
Output:
HashSet contains: AA BB CC DD
HashMap example
import java.util.HashMap;
class HashMapDemo{
public static void main(String[] args) {
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(1, "AA");
hmap.put(2, "BB");
hmap.put(3, "CC");
hmap.put(4, "DD");
System.out.println("HashMap contains: "+hmap); } }

Output:
HashMap contains: {1=AA, 2=BB, 3=CC, 4=DD}
Count Occurrences of a Word in File
Examples:
Input : string = "GeeksforGeeks A computer science
portal for geeks"
word = "portal"
Output : Occurrences of Word = 1 Time
Input : string = "GeeksforGeeks A computer science
portal for geeks"
word = "technical“
Output : Occurrences of Word = 0 Time

Approach :-
•First, we split the string by spaces in a
•Then, take a variable count = 0 and in every true condition we
increment the count by 1
•Now run a loop at 0 to length of string and check if our string is equal
to the word
•if condition true then we increment the value of count by 1 and in the
end we print the value of count.
import java.io.*;
class GFG {
static int countOccurences(String str, String word)
{
// split the string by spaces in a
String a[] = str.split(" ");
// search for pattern in a
int count = 0;
for (int i = 0; i < a.length; i++)
{
// if match found increase count
if (word.equals(a[i]))
count++;
}
return count;
}
public static void main(String args[])
{
String str = "GeeksforGeeks A computer science portal for geeks ";
String word = "portal";
System.out.println(countOccurences(str, word));
}
}

S-ar putea să vă placă și