简体   繁体   中英

Stream do different something with first and last item, Java 8

I have this code, Can to do using tipically

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

        }
      }
}

But I want to know if is it Possible using Java 8 Stream, aditionally

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

Probably better to handle first and last separately

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

Probably worth adding some check of the length for recursivePaths

You can chop your sequence by going via a List then using subList .

I'm not exactly sure what you are trying to do, but you may find Stream.reduce useful. You probably know that non-effectively finals from outside cannot be used in a lambda.

IMO, streams typically make code more difficult to understand, though they are very clever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM