开发者社区> 问答> 正文

将文件中的键值对添加到Hashmap中

我试图从文件中提取键值对到Hashmap,以便更容易地操作值。

该文件采用以下格式:

Activity1:3:Activity2:5:Activity3:7: Activity4:1: 每行最多有3个活动及其相应的编号。

String currentPath; Path fullPath; HashMap<String, String> hm = new HashMap<>();

try { // Obtain current directory path currentPath = Paths.get("").toAbsolutePath().toString(); // Obtain full path of data.txt fullPath = Paths.get(currentPath, "data.txt"); // Check if file exists if (Files.exists(fullPath)) { // Read line by line in data.txt Files.lines(fullPath) .forEach(line -> hm.put(line.split(":")[0], line.split(":")[1]) ); } else{ System.out.println("data.txt is not found."); } } catch ( IOException e) { e.printStackTrace(); } 但是,只有第一个键:值对插入到Hashmap中。我试着用

.map(s -> s.split(":")) .collect(Collectors.toMap(r -> r[0], r -> r[1] )) 但它不起作用,因为split()输出类型是一个toMap不接受的数组。

编辑:

public static void main(String[] args) {

    String currentPath;
    Path filePath;
    HashMap<String, String> hm = new HashMap<>();
    Pattern delimiter = Pattern.compile(":");

    try {
        // Obtain current directory path
        currentPath = Paths.get("").toAbsolutePath().toString();
        // Obtain full path of data.txt
        filePath = Paths.get(currentPath, "data.txt");
        // Check if file exists
        if (Files.exists(filePath)) {
            // Read line by line in data.txt
                hm = Files.lines(filePath)
                    .map(delimiter::split) // stream of multiple Array<String>
                    .flatMapToInt(a -> IntStream.range(0, a.length - 1))  // combine multiple Array<String> to a
                        // single stream, remove last Array<String>
                    .filter(i -> i % 2 == 0)  // obtain only even indices
                    .mapToObj(i -> new AbstractMap.SimpleEntry<>(a[i], a[i+1])) // a cannot be resolved. Create new Map, key is Array<String>[even], value is Array<String>[odd]
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a,b) -> a)); //
        }
        else{
            System.out.println("data.txt not found.");
        }
    } catch (
            IOException e) {
        e.printStackTrace();
    }

    for (String objectName : hm.keySet()) {
        System.out.println(objectName);
        System.out.println(hm.get(objectName));
    }
}

展开
收起
小六码奴 2019-08-17 19:05:17 2268 0
1 条回答
写回答
取消 提交回答
  • 当你在分隔符周围分割每一行时:,可能会有许多键值对。但是你只考虑第一个键值对而省略其余的。因此,这适用于示例中的最后一行,因为它只有一个相应的映射条目。同时它不适用于第一行,因为它只处理第一个条目时有许多相应的映射条目。

    这是我解决这个问题的方法。获取文件中的每一行并将其拆分为分隔符:。这为每个相应的行产生一个数组。由于每一行都有一个尾随:字符,因此必须跳过数组中相关的最后一个元素。然后,数组中的每个偶数指数成为映射中的键,紧随其后的奇数索引成为对应的值。这是它的外观。

    private static final Pattern DELIMITER = Pattern.compile(":"); Map<String, String> activityMap = lines.map(DELIMITER::split) .flatMap(a -> IntStream.range(0, a.length - 1).filter(i -> i % 2 == 0) .mapToObj(i -> new AbstractMap.SimpleEntry<>(a[i], a[i + 1]))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a)); 输出看起来像这样:

    {Activity3 = 7,Activity4 = 1,Activity1 = 3,Activity2 = 5}

    2019-08-17 19:06:31
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载