如何使用Java 8 Stream将csv转换为地图 [英] How to convert csv to a map using Java 8 Stream

查看:368
本文介绍了如何使用Java 8 Stream将csv转换为地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的解析工具,它可以转换两列CSV文件并将其放入地图中。

I'm trying to create a simple parsing util that converts a two-column CSV file and put it into a map.

public Map<String, String> getMapFromCSV(final String filePath) throws IOException {
    return Files.lines(Paths.get(filePath))
                .map(line -> line.split(","))
                .collect(Collectors.toMap(line -> line[0], line -> line[1]));
}

正如你所看到的,我正在创建一个字符串流,分隔每个字符串在逗号上行,并将其转换为字符串数组,最后将键映射到索引0,将值映射到索引1.

As you can see, I'm creating a stream of strings, delimiting each line on a comma and transforming it into a string array, and finally mapping key to index 0 and value to index 1.

@Test
public void testGetMapFromCSV() throws IOException{
    actual = util.getMapFromCSV(filePath).get("AL");
    expected = "ALABAMA";

    assertEquals(expected, actual);
}

出于某种原因,当我运行此测试时,实际值为null。我排除了无效的filePath,因为它在另一个单元测试中工作正常,并且键值存在于CSV中。我一直在盯着它看几个小时,想想也许这里有人可以指出我的错误。

For some reason, when I run this test, the actual value is null. I ruled out invalid filePath because it's working fine in another unit test, and the key value is present in the CSV. I've been staring at it for a few hours now, figured maybe someone here could point out my error.

另外,我对Java 8还不熟悉,所以如果有人知道更好/更清晰的写作方式,我会很感激反馈。

Also, I'm fairly new to Java 8, so if anyone knows a better/cleaner way of writing this, I'd appreciate the feedback.

推荐答案

好的,我添加了 lines.close()并从csv中删除了任何空格它的工作原理!奇怪的是,考虑到csv在我的其他方法中被解析得很好。这是它的样子:

Ok, I added lines.close() and removed any whitespace from the csv and it works! Strange, considering the csv got parsed fine in my other method. Here's what it looks like:

public static Map<String, String> getMapFromCSV(final String filePath) throws IOException{

        Stream<String> lines = Files.lines(Paths.get(filePath));
        Map<String, String> resultMap = 
                lines.map(line -> line.split(","))
                     .collect(Collectors.toMap(line -> line[0], line -> line[1]));

        lines.close();

        return resultMap;
    }

这篇关于如何使用Java 8 Stream将csv转换为地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆