流对第一项和最后一项做不同的事情,Java8

流对第一项和最后一项做不同的事情,Java8,java,java-stream,Java,Java Stream,我有这个代码,可以用TIPICALY做 private static final String FS = System.getProperty("file.separator"); JFileChooser folderChooser = new JFileChooser(); if (folderChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { String filename = folderChooser

我有这个代码,可以用TIPICALY做

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) {

        }
      }
}
但我想知道,是否可以使用Java8流,作为一种传统方式

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?
      });
}

您可以通过
列表
然后使用
子列表
来切碎序列

我不太清楚您想做什么,但您可能会发现
Stream.reduce
很有用。您可能知道,外部的非有效决赛不能用于lambda


在我看来,流通常会使代码更难理解,尽管它们非常聪明。

可能最好先处理后处理

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
    });
  });
}

可能值得为
递归路径

添加一些长度检查,因为它实际上并不是为这种事情而设计的。您可能可以破解它,但它会在以后引入潜在的维护问题。流永远不会结束…在您的循环中,您也不会识别最后一个元素。那你为什么突然想用这条小溪来做呢?此外,使用
getNextMatch
的整个操作看起来很容易出错。如果您的树在节点下包含
Foo
FooBar
,但用户选择了
FooBar
,该怎么办?