These are the coding questions that i have practices using hashmap in java ?
- Print the frequency of each character from the string ?
p 1
a 1
s 1
d 1
e 2
n 1
public static void printFrequency(String s) {
HashMap<Character, Integer> map = new HashMap();
char arr[] = s.toCharArray();
for (char char1 : arr) {
if (map.containsKey(char1))
{
// get the value
int originalValue = map.get(char1);
// and then store it back by incrementing
map.put(char1, ++originalValue);
}
else {
map.put(char1, 1);
}
}
for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
Output based question on hashmap
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Test {
enum Animals {
LION,DOG,COW;
}
public static void main(String args[]) {
Map<Color,String> map=new HashMap<>();
map.put(new Color("Red"),"Red");
map.put(new Color("Blue"),"Blue");
map.put(new Color("Green"),"Green");
map.put(new Color("Blue"),"Blue");
map.put(new Color("Blue"),"Blue");
map.put(new Color("Blue"),"Blue");
// size will be 6 since everytime new hashode is generated and new memeory is used
// whcih is used as key in the above mentionded code
System.out.println(map.size());
map.forEach((k,v)-> System.out.println(k+" : "+ v));
//below mentioned line output is null since
// everytime we are creating new object -> new memory location is used
// amd hence new hashcode wil be generated
System.out.println(map.get(new Color("Blue")));
}
}
class Color {
private String name;
public Color(String name) {
this.name=name;
}
}
Output based Question on HashMap
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
// program to sort the array in reverse oder using Comparator
public class Test {
public static void main(String args[]) {
Map<Color,String> map = new HashMap<>();
map.put(new Color("Red"), "Red");
map.put(new Color("Blue"), "Blue");
map.forEach((k,v) -> System.out.println(k+" : "+v));
map.put(new Color("Green"), "Green");
//1
// System.out.println(map.size());
map.forEach((k,v) -> System.out.println(k+" : "+v));
// Green
System.out.println(map.get(new Color("Red")));
}
}
class Color {
private String name;
public Color(String name) {
this.name=name;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.name;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return true;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return 1;
}
}
- in the above mentioned question -> since the hashCode is returning 1 -> when we are putting the object in the map -> it will always replace the object which is alreayd there and hashCode of all the objects will be 1 in this case