Search This Blog

Breaking

Wednesday, 3 March 2021

HashMap vs LikedHashMap ->How it make difference?

 So there is a standard problem that is given at most of the interview problems. It is the Printing frequency of characters from the given string. 

So when I was asked this question in one of the interviews, I immediately created a hashmap. 

And with the help of that, I find the occurrence of each character.

String s = "deepakmathpal";

char[] charArray = s.toCharArray();

HashMap<Character, Integer> basemap = new HashMap<>();

for(char c:charArray) {

if(basemap.containsKey(c)) {

basemap.put(c, basemap.get(c)+1);

} else {

basemap.put(c, basemap.get(c)+1);

  }

}

basemap.forEach((key,value) -> {

System.out.print(key + ": " );

System.out.print(value);

});





This printed the frequency as:

p: 2

a: 3

d: 1

t: 1

e: 2

h: 1

k: 1

l: 1

m: 1


Did you notice one thing here? Though the output is printing occurrence, however, it is not following the order. If it has followed the order, then below should be the output.

d: 1

e: 2

p: 2

a: 3

k: 1

m: 1

t: 1

h: 1

l: 1

The reason behind this is because the hashmap does not adhere to the insertion order. If you need to process items maintaining the insertion order, you should create a linked hashmap.


So instead of this line: 

HashMap<Character, Integer> basemap = new HashMap<>();


if we use:

HashMap<Character, Integer> basemap = new LinkedHashMap<>();

We will get the output following the order as well.

This will help us if we need to find out the first repeating character from the string:

System.out.println("----------------Printing first recurring-------------------------------------------------" );

String value = basemap.entrySet().stream().filter(entry -> entry.getValue()>1).findFirst().toString();

System.out.println(value );


Check out the difference by running this program with hashmap and linked hashmap.

Till then, happy learning.


No comments:

Post a Comment