commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Thomas Muller" <...@online.no>
Subject RE: [collections] Sort map by value
Date Thu, 06 Feb 2003 13:41:32 GMT
Seems like the association between item and title is so strong that the
title should be an inherent part, but anyway...

I don't know of any map implementations that facilitates sorting by values,
but you can always sort it on demand:

private static Comparator ENTRY_VALUE_COMPARATOR = new Comparator() {

        public int compare( Object o1, Object o2 ) {
            return ( ( Comparable ) ( ( Map.Entry )
o1 ).getValue() ).compareTo( ( ( Map.Entry ) o1 ).getValue() );
        }

   }

Map.Entry[] entries = ( Map.Entry[] ) map.entrySet().toArray( new
Map.Entry[ 0 ] );

Arrays.sort( entries, ENTRY_VALUE_COMPARATOR );

If you want to keep the entries in a sorted structure, you need to maintain
a sorted list / queue parallell to the map. I've attached a couple of
homegrown classes: SortedList and SimpleSortedList you can play with if you
want to.

Hope this helps,

--

Thomas



| -----Original Message-----
| From: Willie Vu [mailto:ctwillie@ust.hk]
| Sent: 06 February 2003 07:28
| To: commons-user@jakarta.apache.org
| Subject: [collections] Sort map by value
|
|
| I've a map where the key is to lookup an item and the value is a title for
| display.  The titles are not unique.  I want to sort the map by
| the titles.
| SortedMap only sorts by key.  DoubleOrderedMap forces values to be unique.
| Neither satisfies my requirement.  Does anyone know a map implementation
| that does what I want?
|
| --
| Willie Vu
|
|
|
| ---------------------------------------------------------------------
| To unsubscribe, e-mail: commons-user-unsubscribe@jakarta.apache.org
| For additional commands, e-mail: commons-user-help@jakarta.apache.org
|
|


*************************************************************************
Copyright ERA Technology Ltd. 2002. (www.era.co.uk). All rights reserved. 
The information supplied in this Commercial Communication should be treated
in confidence.
No liability whatsoever is accepted for any loss or damage 
suffered as a result of accessing this message or any attachments.


________________________________________________________________________
This email has been scanned for all viruses by the MessageLabs SkyScan
service. For more information on a proactive anti-virus service working
around the clock, around the globe, visit http://www.messagelabs.com
________________________________________________________________________
Mime
  • Unnamed multipart/mixed (inline, None, 0 bytes)
View raw message