Way to sort / enforce order for Map.entrySet?

L

laredotornado

Hi,

Does anyone know how to sort a map.entrySet by the value? Each entry
is an Integer mapped to a String, but I wish to have the whole thing
sorted alphabetically by the strings. Any ideas how I can do this?
Below is the function that ultimately serves up the map.entrySet.
(The Map[] object is a list returned from a database).

Thanks, - Dave


@ModelAttribute("promoEntryTypes")
public Set<Map.Entry<String, String>>
populatePromoEntryTypes(@ModelAttribute("appInterface")
JspAppInterfaceAdmin appInterface) {
final Map<String, String> map = new TreeMap<String, String>();
try {
if (appInterface != null) {
Map[] promoEntryTypes = appInterface.getUserPromotionTypes();
for (int i=0; i<promoEntryTypes.length; i++) {
map.put(((Integer) promoEntryTypes.get("id")).toString(),
(String) promoEntryTypes.get("promotion_name"));
} // for
} // if
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return map.entrySet();
}
 
R

Roedy Green

L

Lew

laredotornado said:
Does anyone know how to sort a map.entrySet by the value?  Each entry

Custom Comparator. Load the entries into a SortedSet with that
Comparator.
is an Integer mapped to a String, but I wish to have the whole thing
sorted alphabetically by the strings.  Any ideas how I can do this?
Below is the function that ultimately serves up the map.entrySet.
(The Map[] object is a list returned from a database).

The 'Map[]' object is an unholy moreau of array and raw 'Map'. Ewwww.
    @ModelAttribute("promoEntryTypes")
    public Set<Map.Entry<String, String>>
populatePromoEntryTypes(@ModelAttribute("appInterface")
JspAppInterfaceAdmin appInterface) {
        final Map<String, String> map = new TreeMap<String, String>();
        try {
                if (appInterface != null) {
                        Map[] promoEntryTypes = appInterface.getUserPromotionTypes();
Ewwwwwwwwwwwwwwwwwwwwwwwwwwwww!

                        for (int i=0; i<promoEntryTypes.length; i++) {
                                map.put(((Integer) promoEntryTypes.get("id")).toString(),
(String) promoEntryTypes.get("promotion_name"));
Ewww!

                        }       // for
                }       // if
        } catch (Exception e) {
                log.error(e.getMessage(), e);


At least you're logging, but you're not recovering. And
'catch(Exception...)' is an antipattern in lower-level code.
        }
        return map.entrySet();
    }

That's some fugly code there, bro.
 
M

Mike Schilling

I do use a TreeMap -- "final Map<String, String> map = new
TreeMap<String, String>();", but the order is not getting preserved
when I call "map.entrySet".

A SortedMap (like TreeMap) is sorted by keys, not values. (And you said
earlier that the keys are Integers, but here they're Strings, so I'm
confused.)
 
T

Tom Anderson

Does anyone know how to sort a map.entrySet by the value? Each entry is
an Integer mapped to a String, but I wish to have the whole thing sorted
alphabetically by the strings. Any ideas how I can do this? Below is
the function that ultimately serves up the map.entrySet. (The Map[]
object is a list returned from a database).

SortedSet<Map.Entry<String, String>> results = new TreeSet<Map.Entry<String, String>>(new Comparator<>(<Map.Entry<String, String>>) {
public int compare(<Map.Entry<String, String> a, <Map.Entry<String, String> b) {
int d = a.getValue().compareTo(b.getValue());
if (d == 0) d = a.getKey().compareTo(b.getKey());
return d;
}

});
results.addAll(map.entrySet());
return results;

Note that this assumes none of your values are null, and that no pair of
entries with the same value has any null keys.

tom
 
T

Tom Anderson

A SortedMap (like TreeMap) is sorted by keys, not values. (And you said
earlier that the keys are Integers, but here they're Strings, so I'm
confused.)

Somewhere in the middle of the horror, he's doing:

map.put(((Integer) promoEntryTypes.get("id")).toString(), ...

So they're integers, but encoded in what we call 'ASCII-coded decimal'.

tom
 
L

laredotornado

A SortedMap (like TreeMap) is sorted by keys, not values.  (And you said
earlier that the keys are Integers, but here they're Strings, so I'm
confused.)

Somewhere in the middle of the horror, he's doing:

map.put(((Integer) promoEntryTypes.get("id")).toString(), ...

So they're integers, but encoded in what we call 'ASCII-coded decimal'.

tom


Omg, Tom, can I buy you a beer or something? That solution is exactly
what I was looking for. Thanks! - Dave
 
E

Eric Sosman

Do I get a beer, too, then?

Queue<Beer> wall = ...;
assert wall.size() == 99;
while (! wall.isEmpty()) {
System.out.println(wall.size()
+ " bottles of beer on the wall,");
System.out.println(wall.size()
+ " bottles of beer,");
System.out.println("\tYou take one down,");
Beer beer = wall.remove();
System.out.println("\tPass it around,");
lew.consume(beer);
System.out.println(wall.size()
+ " bottles of beer on the wall.\n");
if (! lew.isSober())
throw new IllegalStateException("Lew is looped");
}
assert false; // notreached
 
L

Lew

Tom said:
U did not post teh codez!!!

Oh, so it's not enough to post the answer, you have to do all the work
for the OP, too? I get it. So if one has an answer to give, but
thinks the OP should do SOME of the work themselves, there's no point
in posting the answer? We don't expect people to think and learn and
deduce any more? What kind of programmers will they turn out to be,
then?
Use sigdashes, which comprise two dashes followed by a space.

The internet eats my spaces when I post from a browser. When I post
from Thunderbird it works fine.

Even without sigdashes, it's possible not to quote the sig. You
didn't use sigdashes, and yet somehow by some weird miracle of my
using my brain your sig was not quoted.

I guess the message of your message is that people shouldn't have to
think.
 
T

Tom Anderson

Oh, so it's not enough to post the answer, you have to do all the work
for the OP, too?

Seems so!
I get it. So if one has an answer to give, but thinks the OP should do
SOME of the work themselves, there's no point in posting the answer?
We don't expect people to think and learn and deduce any more? What
kind of programmers will they turn out to be, then?

Ones whose careers depend on continuing to buy me beer.
The internet eats my spaces when I post from a browser.

Ah, yes, someone probably thought that was a feature.
When I post from Thunderbird it works fine.

Even without sigdashes, it's possible not to quote the sig. You didn't
use sigdashes,

I totally always use sigdashes! Are mine being eaten too?
and yet somehow by some weird miracle of my using my brain your sig was
not quoted.

I guess the message of your message is that people shouldn't have to
think.

I do not believe i expressed a normative opinion on the matter.

tom
 
A

Arne Vajhøj

Oh, so it's not enough to post the answer, you have to do all the work
for the OP, too? I get it. So if one has an answer to give, but
thinks the OP should do SOME of the work themselves, there's no point
in posting the answer?

Lots of point just no beer.

Arne
 
L

Lew

Eric said:
Queue<Beer> wall = ...;
assert wall.size() == 99;
while (! wall.isEmpty()) {
System.out.println(wall.size()
+ " bottles of beer on the wall,");
System.out.println(wall.size()
+ " bottles of beer,");
System.out.println("\tYou take one down,");
Beer beer = wall.remove();
System.out.println("\tPass it around,");
lew.consume(beer);
System.out.println(wall.size()
+ " bottles of beer on the wall.\n");
if (! lew.isSober())
throw new IllegalStateException("Lew is looped");
}
assert false; // notreached

I recommend "Loose Cannon" beer from Clipper City Beer in Baltimore, Maryland,
USA.
<www.clippercitybeer.com>
and not merely because "lewscanon.com" was a pun on that expression.

Loose Cannon is very, very hoppy to the point of tasting like a citrus
beverage. That took some getting used to, but by the second glass it was a
favorite.

I'm sipping one now.

They have other specialty brews if you're less enamored of hops.

I prefer Clipper City to Sam Adams, Yuengling and nearly all the local
microbrews I've tasted. They don't use excess malt as a substitute for flavor
or brewing craft.

YMMV.
 
L

Lew

Tom said:
Ones whose careers depend on continuing to buy me beer.

You are the master! I bow to your wisdom!
I totally always use sigdashes! Are mine being eaten too?

You used them, and they worked, but they are ignored by the browser-based
reader I was using at that time, and part of your sig was above them.

Tom said:
I do not believe i [sic] expressed a normative opinion on the matter.

No doubt, but why would I let that spoil my rhetoric?

Mind you, I have no objection to providing code to help the OP.

I do have a real objection to one ignoring advice that lacks every last
freaking detail of the code and prevents the querent from having to do any
work whatsoever. The OP pretended that your answer came out of nowhere, and
that no one else had suggested the same thing, as if the lack of code made the
other answer(s) any less valuable.

If they really didn't see the value of being told,
"Custom Comparator. Load the entries into a SortedSet with that
Comparator."
then they should have *asked* about it. Then when you gave the code for that
(I assume that's what they were really answering, not the post to which they
actually replied) they pretended like you were the first to even suggest such
a thing in answer to their question.

laredotornado, you are not going to make real progress in computer programming
until you grasp how to take a topic suggestion into code. There are wise
people out there, for example Roedy Green, who will give you a signpost to the
restaurant instead of a sandwich. Feed a man a meal and you feed him for an
hour; send him to the diner and you feed him for a lifetime. In this very
thread Roedy gave you good advice, and you threw it away dismissively by
saying only,
I do use a TreeMap --
"final Map<String, String> map = new
TreeMap<String, String>();",
but the order is not getting preserved when I call "map.entrySet".

And you didn't even provide an SSCCE! What is wrong with you?
 
M

Mike Schilling

Lew said:
Feed a
man a meal and you feed him for an hour; send him to the diner and
you feed him for a lifetime.

Build a man a fire, and he's warm for a night, set him on fire, and he's
warm his whole life.
And you didn't even provide an SSCCE! What is wrong with you?

Since he wanted to sort by value, not key, he's correct -- the entry set
won't be sorted the way he wanted.
 
L

Lew

Mike said:
Build a man a fire, and he's warm for a night, set him on fire, and he's
warm his whole life.



Since he wanted to sort by value, not key, he's correct -- the entry set
won't be sorted the way he wanted.

Unless, of course, he uses a custom Comparator that does sort the way he wants.
 
M

Mike Schilling

Lew said:
Unless, of course, he uses a custom Comparator that does sort the way
he wants.

Not Map.entrySet(); that always sorts by the map's keys. (You can *copy*
the result of entrySet() and sort that copy however you like, of course.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,246
Members
46,842
Latest member
MableIwk73

Latest Threads

Top