对于 LinkedHashMultiMap,按顺序遍历特定键的所有值

Iterating through all values for a particular key, in order, for a LinkedHashMultiMap

我想按插入顺序遍历 LinkedHashMultiMap<String,String> (Guava) 的特定键的值。

这可能吗?如果是这样,怎么做?

为什么是 LinkedHashMultiMap?嗯,我现有的数据结构是 HashMultiMap,我想如果我将它更改为 LinkedHashMultiMap,那将与我现有的代码兼容,我可以以某种方式迭代这些值。

但是查看文档,我不太明白 - 也就是说,我是 LinkedHashMultiMap class.

的新手

LinkedHashMultimap is a documented behavior

的插入顺序迭代

Implementation of Multimap that does not allow duplicate key-value entries and that returns collections whose iterators follow the ordering in which the data was added to the multimap.

开箱即用,请参阅 wiki page on Multimap implementations:

| Implementation       | Keys behave like... | Values behave like.. |
|:---------------------|:--------------------|:---------------------|
| LinkedHashMultimap** | LinkedHashMap       | LinkedHashSet        |

`**` `LinkedHashMultimap` preserves insertion order of entries,  
as well as the insertion order of keys, and the set of values associated with any one key.

代码示例:

LinkedHashMultimap<String, String> m = LinkedHashMultimap.create();

m.put("a", "foo");
m.put("b", "bar");
m.put("a", "baz");

m.get("a").forEach(System.out::println); // outputs "foo" and "baz"

只需使用 get,然后在 for-each 循环中迭代结果 Set

for (String value : multimap.get(key)) {

}

集合的迭代器将按照它们被添加到 Multimap 的顺序进行迭代,如 documentation 所指定。

Similarly, get, removeAll, and replaceValues return collections that iterate through the values in the order they were added.