鉴于这张地图
SortedMap<Integer, String> myMap = new TreeMap<Integer, String>();
Run Code Online (Sandbox Code Playgroud)
而不是for循环是否有一个实用功能来将前N个项目复制到目标地图?
Pau*_*aul 19
使用Java 8+的强大功能:
TreeMap<Integer, String> myNewMap = myMap.entrySet().stream()
.limit(3)
.collect(TreeMap::new, (m, e) -> m.put(e.getKey(), e.getValue()), Map::putAll);
Run Code Online (Sandbox Code Playgroud)
也许,但不是标准Java API的一部分.并且:实用程序将在内部使用循环.
所以你需要一个循环,但你可以通过在实用程序类中的静态方法中完成所有操作来创建自己的"实用程序":
public static SortedMap<K,V> putFirstEntries(int max, SortedMap<K,V> source) {
int count = 0;
TreeMap<K,V> target = new TreeMap<K,V>();
for (Map.Entry<K,V> entry:source.entrySet()) {
if (count >= max) break;
target.put(entry.getKey(), entry.getValue());
count++;
}
return target;
}
Run Code Online (Sandbox Code Playgroud)
复杂性仍然是O(n)(我怀疑,一个人可以实现O(1)),但你使用它就像一个没有"看到"循环的工具:
SortedMap<Integer, String> firstFive = Util.putFirstEntries(5, sourceMap);
Run Code Online (Sandbox Code Playgroud)
有SortedMap.headMap()
,但是你会不得不通过一个键上去的元素.你可以迭代N个元素Map.keySet()
来找到它,例如:
Integer toKey = null;
int i = 0;
for (Integer key : myMap.keySet()) {
if (i++ == N) {
toKey = key;
break;
}
}
// be careful that toKey isn't null because N is < 0 or >= myMap.size()
SortedMap<Integer, String> copyMap = myMap.headMap(toKey);
Run Code Online (Sandbox Code Playgroud)