代码之家  ›  专栏  ›  技术社区  ›  QA_Col

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

  •  -2
  • QA_Col  · 技术社区  · 7 年前

    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?
          });
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Joakim Danielson    7 年前

    可能最好先处理后处理

    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

        2
  •  0
  •   Tom Hawtin - tackline    7 年前

    你可以通过一个 List 然后使用 subList

    我不确定你想做什么,但你可能会发现 Stream.reduce

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