番石榴多地图使用TreeMap而不是HashMap?

时间:2021-07-08 16:07:10

I have something like the following:

我有以下几点:

final SortedMap<Integer,List<Integer>> m = new TreeMap<Integer,List<Integer>>();

And I'd like to use google-guava to make this a multimap. However I don't see any implementation that provides a SortedMap holding an ArrayList. I only see HashMap+ArrayList implementation (ArrayListMultimap). Does the implementation that I want exist?

我想用google-guava来做一个多地图。但是,我没有看到任何实现提供包含ArrayList的排序映射。我只看到HashMap+ArrayList实现(ArrayListMultimap)。我想要的实现存在吗?

2 个解决方案

#1


13  

Guava has a TreeMultimap that stores both keys and values in sorted order. However, this uses a TreeSet for the values rather than a List so it may not quite be what you want here. In that case, Guava allows you to create a Multimap that works any way you want using one of the Multimaps.new*Multimap methods, such as Multimaps.newListMultimap. To make one that works like you describe, you'd just write this:

Guava有一个TreeMultimap,它可以按顺序存储密钥和值。但是,它使用树集来表示值,而不是列表,因此它可能不是您在这里想要的。在这种情况下,番石榴允许您创建一个多映射,该多映射可以使用其中的一个Multimaps以任何方式工作。新的多映射方法,如Multimap. newlistmultimap。要做出像你描述的那样的作品,你可以这样写:

Map<Integer, Collection<Integer>> map = Maps.newTreeMap();
ListMultimap<Integer, Integer> m = Multimaps.newListMultimap(map,
    new Supplier<List<Integer>>() {
      public List<Integer> get() {
        return Lists.newArrayList(); // assuming you want to use ArrayList
      }
    });

#2


7  

Here's how you can create that beast:

下面是你如何创造这个野兽:

Multimap<Integer,Integer> multimap = Multimaps.newListMultimap(
    Maps.<Integer, Collection<Integer>>newTreeMap(),
    new Supplier<List<Integer>>() {
        public List<Integer> get() {
            return Lists.newArrayList();
        }
    });

#1


13  

Guava has a TreeMultimap that stores both keys and values in sorted order. However, this uses a TreeSet for the values rather than a List so it may not quite be what you want here. In that case, Guava allows you to create a Multimap that works any way you want using one of the Multimaps.new*Multimap methods, such as Multimaps.newListMultimap. To make one that works like you describe, you'd just write this:

Guava有一个TreeMultimap,它可以按顺序存储密钥和值。但是,它使用树集来表示值,而不是列表,因此它可能不是您在这里想要的。在这种情况下,番石榴允许您创建一个多映射,该多映射可以使用其中的一个Multimaps以任何方式工作。新的多映射方法,如Multimap. newlistmultimap。要做出像你描述的那样的作品,你可以这样写:

Map<Integer, Collection<Integer>> map = Maps.newTreeMap();
ListMultimap<Integer, Integer> m = Multimaps.newListMultimap(map,
    new Supplier<List<Integer>>() {
      public List<Integer> get() {
        return Lists.newArrayList(); // assuming you want to use ArrayList
      }
    });

#2


7  

Here's how you can create that beast:

下面是你如何创造这个野兽:

Multimap<Integer,Integer> multimap = Multimaps.newListMultimap(
    Maps.<Integer, Collection<Integer>>newTreeMap(),
    new Supplier<List<Integer>>() {
        public List<Integer> get() {
            return Lists.newArrayList();
        }
    });