Home > Blockchain >  How would I assign these to variables rather then print the paths?
How would I assign these to variables rather then print the paths?

Time:02-26

I have this class and method, that does a file walk to one level of hierarchy, but I don't know how to assign these to variables after they have been found instead of printing them. How would I do this?

package modloaderx2;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class findMods {

    public static void find(String glob, String location) throws IOException {
     
         try (Stream<Path> paths = Files.walk(Paths.get(location), 1)) 
                {paths.filter(Files::isDirectory).forEach(System.out::println);

         }   
    }
}

CodePudding user response:

if i understood correctly, you want a filtered collection from the files ?

In that case dont use .forEach() it is a consumer (consumes input and returns nothing)

so simply use .collect at the end, and pick the one method that fits yo. usually I use this one, but there are many more.

paths.filter(Files::isDirectory)
     .collect(Collectors.asList());

Please check autocompletion, I am writing it from my memory right now.

  •  Tags:  
  • java
  • Related