Way to sort / enforce order for Map.entrySet?

Discussion in 'Java' started by laredotornado, Apr 23, 2010.

  1. 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();
    }
    laredotornado, Apr 23, 2010
    #1
    1. Advertising

  2. laredotornado

    Roedy Green Guest

    On Fri, 23 Apr 2010 06:51:15 -0700 (PDT), laredotornado
    <> wrote, quoted or indirectly quoted someone
    who said :

    >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.


    Generally it is simpler to sort just before you need the data is
    order. See http://mindprod.com/jgloss/sort.html

    If you need the sorted order all the time use a TreeSet or its brother
    TreeMap.

    http://mindprod.com/jgloss/treemap.html
    http://mindprod.com/jgloss/treeset.html
    --
    Roedy Green Canadian Mind Products
    http://mindprod.com

    It’s amazing how much structure natural languages have when you consider who speaks them and how they evolved.
    Roedy Green, Apr 23, 2010
    #2
    1. Advertising

  3. laredotornado

    Lew Guest

    laredotornado wrote:
    > 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.

    --
    Lew
    Lew, Apr 23, 2010
    #3
  4. On Apr 23, 9:15 am, Roedy Green <>
    wrote:
    > On Fri, 23 Apr 2010 06:51:15 -0700 (PDT), laredotornado
    > <> wrote, quoted or indirectly quoted someone
    > who said :
    >
    > >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.

    >
    > Generally it is simpler to sort just before you need the data is
    > order. Seehttp://mindprod.com/jgloss/sort.html
    >
    > If you need the sorted order all the time use a TreeSet or its brother
    > TreeMap.
    >
    > http://mindprod.com/jgloss/treemap.htmlhttp://mindprod.com/jgloss/treeset..html
    > --
    > Roedy Green Canadian Mind Productshttp://mindprod.com
    >
    > It’s amazing how much structure natural languages have when you consider who speaks them and how they evolved.



    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". - Dave
    laredotornado, Apr 23, 2010
    #4
  5. laredotornado wrote:
    > On Apr 23, 9:15 am, Roedy Green <>
    > wrote:
    >> On Fri, 23 Apr 2010 06:51:15 -0700 (PDT), laredotornado
    >> <> wrote, quoted or indirectly quoted
    >> someone
    >> who said :
    >>
    >>> 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.

    >>
    >> Generally it is simpler to sort just before you need the data is
    >> order. Seehttp://mindprod.com/jgloss/sort.html
    >>
    >> If you need the sorted order all the time use a TreeSet or its
    >> brother
    >> TreeMap.


    >
    > 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.)
    Mike Schilling, Apr 23, 2010
    #5
  6. laredotornado

    Tom Anderson Guest

    On Fri, 23 Apr 2010, laredotornado wrote:

    > 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

    --
    Per Dementia ad Astra
    Tom Anderson, Apr 23, 2010
    #6
  7. laredotornado

    Tom Anderson Guest

    On Fri, 23 Apr 2010, Mike Schilling wrote:

    > laredotornado wrote:
    >> On Apr 23, 9:15 am, Roedy Green <>
    >> wrote:
    >>> On Fri, 23 Apr 2010 06:51:15 -0700 (PDT), laredotornado
    >>> <> wrote, quoted or indirectly quoted someone
    >>> who said :
    >>>
    >>>> 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.

    >
    > 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

    --
    Per Dementia ad Astra
    Tom Anderson, Apr 23, 2010
    #7
  8. On Apr 23, 11:59 am, Tom Anderson <> wrote:
    > On Fri, 23 Apr 2010, Mike Schilling wrote:
    > > laredotornado wrote:
    > >> On Apr 23, 9:15 am, Roedy Green <>
    > >> wrote:
    > >>> On Fri, 23 Apr 2010 06:51:15 -0700 (PDT), laredotornado
    > >>> <> wrote, quoted or indirectly quoted someone
    > >>> who said :

    >
    > >>>> 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.

    >
    > > 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
    >
    > --
    > Per Dementia ad Astra


    Omg, Tom, can I buy you a beer or something? That solution is exactly
    what I was looking for. Thanks! - Dave
    laredotornado, Apr 23, 2010
    #8
  9. laredotornado

    Lew Guest

    laredotornado wrote:
    >> tom
    >>
    >> --
    >> Per Dementia ad Astra

    >


    Don't quote sigs.

    > Omg, Tom, can I buy you a beer or something?  That solution is exactly
    > what I was looking for.
    >


    Do I get a beer, too, then?

    --
    Lew
    Don't quote sigs, in particular not this one.
    Lew, Apr 23, 2010
    #9
  10. laredotornado

    Eric Sosman Guest

    On 4/23/2010 2:25 PM, Lew wrote:
    > laredotornado wrote:
    >>
    >> Omg, Tom, can I buy you a beer or something? That solution is exactly
    >> what I was looking for.
    >>

    >
    > 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

    --
    Eric Sosman
    lid
    Eric Sosman, Apr 23, 2010
    #10
  11. laredotornado

    Tom Anderson Guest

    On Fri, 23 Apr 2010, Lew wrote:

    > laredotornado wrote:
    >
    >> Omg, Tom, can I buy you a beer or something?  That solution is exactly
    >> what I was looking for.

    >
    > Do I get a beer, too, then?


    U did not post teh codez!!!

    > --
    > Lew
    > Don't quote sigs, in particular not this one.


    Use sigdashes, which comprise two dashes followed by a space.

    tom

    --
    CRESS AND CREATIVITY GET BUSY -- Barry
    Tom Anderson, Apr 23, 2010
    #11
  12. laredotornado

    Lew Guest

    laredotornado wrote:
    >>> Omg, Tom, can I buy you a beer or something? ï¿œThat solution is exactly
    >>> what I was looking for.

    >


    Lew wrote:
    >> Do I get a beer, too, then?

    >


    Tom Anderson wrote:
    > 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?

    >> --
    >> Lew
    >> Don't quote sigs, in particular not this one.

    >


    > 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.

    --
    Lew
    Lew, Apr 23, 2010
    #12
  13. laredotornado

    Tom Anderson Guest

    On Fri, 23 Apr 2010, Lew wrote:

    > laredotornado wrote:
    >>>> Omg, Tom, can I buy you a beer or something? ???That solution is exactly
    >>>> what I was looking for.

    >>

    > Lew wrote:
    >>> Do I get a beer, too, then?

    >>

    > Tom Anderson wrote:
    >> 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?


    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.

    >>> --
    >>> Lew
    >>> Don't quote sigs, in particular not this one.

    >>
    >> Use sigdashes, which comprise two dashes followed by a space.

    >
    > 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

    --
    CRESS AND CREATIVITY GET BUSY -- Barry
    Tom Anderson, Apr 23, 2010
    #13
  14. laredotornado

    Arne Vajhøj Guest

    On 23-04-2010 15:24, Lew wrote:
    > laredotornado wrote:
    >>>> Omg, Tom, can I buy you a beer or something? ï¿œThat solution is exactly
    >>>> what I was looking for.

    >
    > Lew wrote:
    >>> Do I get a beer, too, then?

    >
    > Tom Anderson wrote:
    >> 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?


    Lots of point just no beer.

    Arne
    Arne Vajhøj, Apr 24, 2010
    #14
  15. laredotornado

    Jeff Higgins Guest

    On 4/23/2010 7:24 PM, Arne Vajhøj wrote:
    > Lots of point just no beer.

    Uumm, beer.
    Jeff Higgins, Apr 24, 2010
    #15
  16. laredotornado

    Lew Guest

    laredotornado wrote:
    >>> Omg, Tom, can I buy you a beer or something? That solution is exactly
    >>> what I was looking for.


    Lew wrote:
    >> Do I get a beer, too, then?


    Eric Sosman wrote:
    > 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.

    --
    Lew
    Lew, Apr 24, 2010
    #16
  17. laredotornado

    Lew Guest

    Lew wrote:
    >> 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?


    Tom Anderson wrote:
    > 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.

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


    Tom Anderson wrote:
    > 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?

    --
    Lew
    Lew, Apr 24, 2010
    #17
  18. Lew wrote:
    > 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.

    >> 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?


    Since he wanted to sort by value, not key, he's correct -- the entry set
    won't be sorted the way he wanted.
    Mike Schilling, Apr 24, 2010
    #18
  19. laredotornado

    Lew Guest

    Mike Schilling wrote:
    > Lew wrote:
    >> 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.
    >
    >>> 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?

    >
    > 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.

    --
    Lew
    Lew, Apr 24, 2010
    #19
  20. Lew wrote:
    > Mike Schilling wrote:
    >> Lew wrote:
    >>> 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.
    >>
    >>>> 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?

    >>
    >> 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.


    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.)
    Mike Schilling, Apr 24, 2010
    #20
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Steve Green

    HashMap<> entrySet

    Steve Green, Mar 25, 2005, in forum: Java
    Replies:
    2
    Views:
    2,328
    Steve Green
    Mar 25, 2005
  2. =?ISO-8859-1?Q?Sacha_Sch=E4r?=

    How to enforce execution order?

    =?ISO-8859-1?Q?Sacha_Sch=E4r?=, Jan 31, 2006, in forum: C++
    Replies:
    14
    Views:
    668
    Catalin Marinas
    Feb 2, 2006
  3. ankur
    Replies:
    2
    Views:
    2,298
    ankur
    Feb 23, 2009
  4. Rakesh
    Replies:
    3
    Views:
    4,205
    Tom Anderson
    Mar 10, 2009
  5. Phlip
    Replies:
    8
    Views:
    1,000
    Phlip
    Mar 18, 2009
Loading...

Share This Page