流对第一个项目和最后一个项目(Java 8)执行不同的操作

时间:2019-01-13 19:11:26

标签: java java-stream

我有这段代码,可以使用

private static final String FS = System.getProperty("file.separator");
JFileChooser folderChooser = new JFileChooser();
if (folderChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
      String filename = folderChooser.getSelectedFile().getPath();
      String[] recursivePaths = filename.split(FS);
      TreePath treePath = null;
      for (String part : recursivePaths) {
        int row = (treePath == null ? 0 : treePaths.getRowForPath(treePath));
        treePath = treePaths.getNextMatch(part, row, Position.Bias.Forward);
        if (treePath == null) {

        }
      }
}

但是我想知道是否可以使用Java 8 Stream

private static final String FS = System.getProperty("file.separator");
JFileChooser folderChooser = new JFileChooser();
if (folderChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
      String filename = folderChooser.getSelectedFile().getPath();
      String[] recursivePaths = filename.split(FS);
      Stream.of(recursivePaths).forEach(partFile -> {
          // Do something with FIRST, But How Discover?
          // Do something with OTHERS
          // Do something with LAST, But How Discover?
      });
}

2 个答案:

答案 0 :(得分:2)

最好分别处理第一个和最后一个

private static final String FS = System.getProperty("file.separator");
JFileChooser folderChooser = new JFileChooser();
if (folderChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
    String filename = folderChooser.getSelectedFile().getPath();
    String[] recursivePaths = filename.split(FS);
    String first = recursivePaths[0];
    String last = recursivePaths[recursivePaths.length - 1];

    Arrays.stream(recursivePaths, 1, recursivePaths.length - 1).forEach( x -> {
       //stream the elements in the middle
    });
  });
}

可能值得为recursivePaths添加一些长度检查

答案 1 :(得分:0)

您可以先通过List然后使用subList来剪切序列。

我不确定您要做什么,但是您可能会发现Stream.reduce有用。您可能知道,外部无效的决赛不适用于lambda。

IMO,流虽然很聪明,但是通常会使代码难以理解。