Bob Kuhar
Bob Kuhar

Reputation: 11140

In search of an easier way to get ImmutableMultimap<String, String>'s get to return sorted

I have an ImmutableMultimap and I need to present its values as a sorted list. The following code works, but seems rather inefficient. I am in search of a way "up-front" to set up for the get( value ) method call to just always return a sorted list. I don't see, for example, a class like ImmutableSortedMultimap laying around which would make getting this done obvious. How can I get this done such that the get( value ) call always returns the ImmutableCollection sorted?

private ImmutableMultimap<String, String> FIELDS_TO_TYPES = 
    ProfileTypeManager.getFieldsToTypes();
...
String value = getDataSourceFieldId();
ImmutableCollection<String> types = FIELDS_TO_TYPES.get( value );
display = String.format( "%s %s", display, Ordering.natural().sortedCopy( types ) );

Upvotes: 0

Views: 744

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198211

When you're creating the ImmutableMultimap, ImmutableMultimap.Builder has an orderValuesBy method, so you'd do something like

ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder()
   .orderValuesBy(comparator);
// put values in builder

Upvotes: 2

Related Questions