【发布时间】:2018-12-24 06:21:24
【问题描述】:
我一直在尝试重写以下内容以使用 Stream API。我似乎无法弄清楚如何到达地图(或字段)为 System.setProperty(k,v) 设置键值对
我的数据只是它们之间有空格的行,它们分别被拆分为键和值:
foo bar
mykey myvalue
nextkey nextvalue
我的工作源代码在这里:
try {
Scanner scanner = new Scanner(Paths.get("/path/to/file.txt"));
while(scanner.hasNextLine()){
String line = scanner.nextLine();
String[] array = line.split(" ");
if(array.length == 2){
System.setProperty("twitter4j.oauth." + array[0], array[1]);
}
}
} catch (IOException e) {
e.printStackTrace();
}
在这里放一个损坏的样本,虽然我一直在尝试用流编写它(呻吟),但这里是它的一个迭代,只是为了证明我尝试过:-p
Stream<String> lines = null;
try {
lines = Files.lines(Paths.get("/Users/bellis/dev/data/twitter.txt"));
} catch (IOException e) {
e.printStackTrace();
}
String[] words = lines.collect((Collectors.joining("\n"))).split(" ");
System.out.println("twitter4j.oauth." + words[0] + " " + words[1]);
上述内容当然是不正确的,我知道使用函数和其他常见的 Stream 习惯用法有很多更好的方法来编写它,但我似乎无法做到正确。 您如何建议使用 Stream 和函数式 API 编写此代码?
【问题讨论】:
-
@nullpointer 上面的尝试当然会编译,但它并没有通过每一行。我现在意识到我没有在尝试中添加 System.setProperty() -这可能会使我的问题令人困惑。但是,我从来没有像我的原始代码那样做任何事情,即为文件中的每一行设置一个系统属性。
-
为什么一个很好的问题会被拒绝?提出问题不是为了更好地理解吗?
标签: java java-8 functional-programming java-stream