如何从HashMap或LinkedHashMap获取有限数量的值?

Adn*_*Ch. 3 java hashmap linkedhashmap

假设我有一个LinkedHashMap包含216个条目,我如何Object从a 获得前100个值(此处为类型)LinkedHashMap<Integer, Object>.

Jon*_*eet 5

好吧,首先,HashMap根据你的标题这样做,没有多大意义 - HashMap没有特定的顺序,并且订单可能在不同的电话之间改变.LinkedHashMap尽管如此,它更有意义.

在那里,我会使用番石榴Iterables.limit方法:

Iterable<Object> first100Values = Iterables.limit(map.values(), 100);
Run Code Online (Sandbox Code Playgroud)

要么

// Or whatever type you're interested in...
Iterable<Map.Entry<Integer, Object>> firstEntries =
    Iterables.limit(map.entrySet(), 100);
Run Code Online (Sandbox Code Playgroud)

然后,您可以从中创建一个列表,或者迭代它,或者您想要做的任何事情.