英文:
Multiple filters on a Path i.e. file
问题
我对以下代码有一个问题:
```java
import java.io.*
import java.nio.*
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public static void FileReader {
String filePath = "C:\\Downloads\\";
Stream<Path> walk = Files.walk(Paths.get(filePath));
List<Resource> result = walk
.map(file -> file.toString())
.filter(file -> file.endsWith(".json"))
.map(file -> new FileSystemResource(file))
.collect(Collectors.toList());
walk.close();
}
你是否可以在文件上有多个过滤器,比如一个用于文件是否以 .zip
结尾?
<details>
<summary>英文:</summary>
I have a question on the following code:
```java
import java.io.*
import java.nio.*
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public static void FileReader {
String filePath = "C:\Downloads\"";
Stream<Path> walk = Files.walk(Paths.get(filePath));
List<Resource> result = walk
.map(file -> file.toString())
.filter(file -> file.endsWith(".json"))
.map(file -> new FileSystemResource(file))
.collect(Collectors.toList());
walk.close()
}
Can you have multiple filters on file, such as one for if the file ends in .zip
?
答案1
得分: 1
总之 - 是的。
首先,您的筛选器可以包含多个条件,这些条件可以用一些逻辑运算符连接在一起,例如:
List<Resource> result = walk
.map(file -> file.toString())
.filter(file -> file.endsWith(".json") || file.endsWith(".zip"))
.map(file -> new FileSystemResource(file))
.collect(Collectors.toList());
其次,您可以有多个filter
调用,并且可以在终止调用之前的任何地方混合它们,例如:
List<Resource> result = walk
.map(file -> file.toString())
.filter(file -> file.endsWith(".json"))
.map(file -> new FileSystemResource(file))
.filter(f -> f != null) // 或者更有意义的条件...
.collect(Collectors.toList());
英文:
In a word - yes.
First, your filter could contain several conditions joined together with some logical operator, e.g.:
List<Resource> result = walk
.map(file -> file.toString())
.filter(file -> file.endsWith(".json") || file.endsWith(".zip")
.map(file -> new FileSystemResource(file))
.collect(Collectors.toList());
Second, you could have multiple filter
calls and you can mix them up anywhere before the terminating call, e.g.:
List<Resource> result = walk
.map(file -> file.toString())
.filter(file -> file.endsWith(".json"))
.map(file -> new FileSystemResource(file))
.filter(f -> f != null) // Or something more meaningful...
.collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论