如何重写此代码以使用Stream和功能API?

Bra*_*lis -2 java functional-programming java-8 java-stream

我一直在尝试重写以下内容以使用Stream API.我似乎无法弄清楚如何到Map(或字段)为System.setProperty(k,v)设置键值对

我的数据只是在它们之间有空格的行,它们分别分为键和值:

foo bar
mykey myvalue
nextkey nextvalue
Run Code Online (Sandbox Code Playgroud)

我的工作源代码在这里:

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();
}
Run Code Online (Sandbox Code Playgroud)

在这里放一个破碎的样本,虽然我已经遍布地图(呻吟)试图用流写它,但这里只是为了证明我尝试了一次迭代:-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]);
Run Code Online (Sandbox Code Playgroud)

上面当然是不正确的我知道有更好的方法来使用函数和其他常见的流成语来编写它,但我似乎无法做到正确.您如何建议使用Stream和功能API编写此代码?

Ous*_* D. 5

你的流尝试完全没有了.这就是你的命令式代码所做的.

try (Stream<String> stream = Files.lines(Paths.get("/path/to/file.txt"))) {
         stream.map(line -> line.split(" "))
               .filter(array -> array.length == 2)
               .forEach(array -> System.setProperty("twitter4j.oauth." + array[0], array[1]));    
} catch (IOException e) { e.printStackTrace(); }
Run Code Online (Sandbox Code Playgroud)
  • 将每一行映射到a String[]
  • 过滤它们以保留长度恰好为2的元素
  • 然后调用forEach将函数应用于每个元素.