• Post Reply Bookmark Topic Watch Topic
  • New Topic

TreeSet sorted from HashMap  RSS feed

 
Ken Jenning
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I'm new to Java.

I want to get the biggest value from the HashMap.

How do I get back cherries & plum since they both have "45"?

 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, the only mapping (of keys to values) that you have is the hashmap, so you will need to iterate through the entry set of the hashmap looking for the keys that map to a particular value.

Henry
 
Campbell Ritchie
Marshal
Posts: 56595
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Are you sure you want to use a TreeSet specifically? A set does not support duplicates, so you won't have 45 in twice. Consider reversing the mapping so your Map<Fruit, Integer> turns in to a Map<Integer, Fruit>. No, that won't give you duplicates, either, so change that to Map<Integer, List<Fruit>>. You can probably get that out of a Stream with the groupingBy method, but that would be an ordinary Map rather than a sorted Map.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'd indeed need groupingBy, but that's not enough. Using a simple groupingBy with only the mapping function (Map.Entry::getValue) would yield a Map<Integer, List<Map.Entry<String, Integer>>>. That has the wrong map type, and the wrong value type.

First of all, to get a SortedMap instead of a "generic" Map (which is probably a HashMap), you'll need the 3-argument groupingBy variant with TreeMap::new as the 2nd argument. Using Collectors.toList() as the 3rd argument would yield a SortedMap<Integer, List<Map.Entry<String, Integer>>>. That's almost good, except the map values. We need to use Collectors.mapping for that to change Map.Entry<String, Integer> into the map keys:
 
Campbell Ritchie
Marshal
Posts: 56595
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My, isn't that elegant code
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!