javacollectionsguava

How to build a ImmutableListMultimap with sorted values


I am trying to build an ImmutableListMultimap which has sorted values. I tried the following but toImmutableListMultimap supports only value mapper and not the list of value mapper. Is there any other alternative to this?

Ordering<StatsByDimensions> valueOrdering =
        Ordering.natural().onResultOf(StatsByDimensions::getCost);
ImmutableListMultimap<Dimension, StatsByDimensions> statsByDimenisonMap =
        Multimaps.index(listOfStats, StatsByDimensions::getDimension)
            .asMap()
            .entrySet()
            .stream()
            .collect(
                toImmutableListMultimap(
                    entry -> entry.getKey(),
                    entry -> valueOrdering.immutableSortedCopy(entry.getValue())));

error:

incompatible types: inference variable V has incompatible bounds
    equality constraints: path.to.StatsByDimensions
    lower bounds: com.google.common.collect.ImmutableList<E>javac

Solution

  • Sure. You don't need to use streams.

    ImmutableListMultimap.Builder<Dimension, StatsByDimensions> statsByDimensionMapBuilder =
        ImmutableListMultimap.builder();
    statsByDimensionMapBuilder.orderValuesBy(
        Comparator.comparing(StatsByDimensions::getCost));
    for (StatsByDimensions statsByDimensions : listOfStats) {
      statsByDimensionMapBuilder.put(
        StatsByDimensions.getDimension(statsByDimensions), statsByDimensions);
    }
    return statsByDimensionMapBuilder.build();