【发布时间】:2019-07-10 03:57:45
【问题描述】:
我有一个包含格式行的文件:
banana::yellow
orange::orange
apple::red
garlic::white
我想将文件读入地图,其中key 是:: 的左侧,值是:: 的右侧
我这样做是为了实现它:
try (Stream<String> stream = Files.lines(Paths.get(myFilePath))) {
List<String> myList = stream.collect(Collectors.toList());
Map<String, String> myMap = new HashMap<>();
for (String line : myList) {
String[] pair = line.split("::");
myMap.put(pair[0], pair[1]);
}
} catch (IOException e) {
e.printStackTrace();
}
但是,这是否可以进一步简化,以便流直接生成我想要的地图?
Map<String, String> myMap = stream.somethinghere ??
谢谢!
【问题讨论】:
标签: java file dictionary java-8 java-stream