java - 使用索引迭代 Java Map

标签 java collections map io writer

如何遍历 Map 以将内容从某个索引写入另一个。

Map<String, Integer> map = new LinkedHashMap<>();
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));

            for (String string : map.keySet()) {

                    bufferedWriter.write(string + " " + map.get(string));
                    bufferedWriter.newLine();

            }
            bufferedWriter.close();

我有两个 int 值,from 和 to,我现在怎么写例如从 10 到 100?有没有可能用索引迭代 map ?

最佳答案

LinkedHashMap 保留插入条目的顺序。所以你可以尝试创建一个键列表并使用索引循环:

List<String> keyList = new ArrayList<String>(map.keySet());
for(int i = fromIndex; i < toIndex; i++) {
    String key = keyList.get(i);
    String value = map.get(key);
    ...
}

另一种不创建列表的方法:

int index = 0;
for (String key : map.keySet()) {
    if (index++ < fromIndex || index++ > toIndex) {
        continue;
    }
    ...
}

关于java - 使用索引迭代 Java Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27300962/

相关文章:

map - SVG map 中的国家/地区名称

c++ - 为什么这个 STL 映射的条目没有在 GCC 4.5.1 中初始化?

Java 集合内存消耗

具有不同 first 和 last 函数的 Haskell map (?) 操作

java - 在tomcat中共享一个文件夹

java - Spring-mvc中的JDBC异常处理

java - 从带有偏移值的日期获取时区信息

java - JSON:Python 输出文件到 Java ObjectMapper - 大小错误

c# - Java - 集合基础

java - 玩!框架: using find() model method on a collection