Hey guys,

I am trying to solve a problem on Leetcode that asks to retrieve the number that occurs the most from an int array. I managed to put all numbers into a hashmap as keys, and values as their occurrence, but I can not figure it out how to retrieve values of n element from a map. (Just started learning Java, maybe I am completely off here :D). Is there a way to get the value of the n key of a map, or only for keys I know what their actual value is? Hope my question makes sense...
7 Replies
JavaBot
JavaBot3mo ago
This post has been reserved for your question.
Hey @orbankaroly! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
dan1st
dan1st3mo ago
yourMap.get(yourKey)? in this case int occurance = yourMap.get(yourNumber);
orbankaroly
orbankarolyOP3mo ago
tried with the .get() method, but if i understand it correctly it works only if i know the key itself i just wanted to iterate through the map and check the values as integers, so i can set the highest to a max variable my workaround was putting the original array's number in a stack, and then going through the stack to get the values out but the code is a mess as much as my posts 😄
dan1st
dan1st3mo ago
oh I didn't notice you wanted to iterate over it you can do something like this if you don't need to return anything from it and also not change local variables:
yourMap.forEach((key, value) -> {
//do something here
});
yourMap.forEach((key, value) -> {
//do something here
});
otherwise you can use a foreach loop:
for(Map.Entry<Integer, Integer> entry : yourMap.entrySet()){
int key = entry.getKey();
int value = entry.getValue();
}
for(Map.Entry<Integer, Integer> entry : yourMap.entrySet()){
int key = entry.getKey();
int value = entry.getValue();
}
orbankaroly
orbankarolyOP3mo ago
ohh cool, thanks a lot!
JavaBot
JavaBot3mo ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
JavaBot
JavaBot3mo ago
Post Closed
This post has been closed by <@232222326022864897>.

Did you find this page helpful?