Java 当过滤器匹配时,如何按启动的流收集数据?
我想用Java8编写代码来保存列表中文本文件中的数据。 我必须使用流。数据必须保存在混凝土线的列表中。 例如: 我的文本文件:Java 当过滤器匹配时,如何按启动的流收集数据?,java,stream,Java,Stream,我想用Java8编写代码来保存列表中文本文件中的数据。 我必须使用流。数据必须保存在混凝土线的列表中。 例如: 我的文本文件: House Tree Pillow Sky 我想用“枕头”(正则表达式)行将数据保存在列表中。 预期结果(在我的列表中): 问题:当filter()匹配时,如何开始将文件中的数据从第行保存到列表中?如果要跳过文件中的前两项,可以执行以下操作: public static void main(String[] args) { String fileNam
House
Tree
Pillow
Sky
我想用“枕头”(正则表达式)行将数据保存在列表中。
预期结果(在我的列表中):
问题:当filter()匹配时,如何开始将文件中的数据从第行保存到列表中?如果要跳过文件中的前两项,可以执行以下操作:
public static void main(String[] args) {
String fileName = "/home/daniel/doc"; //text file location
int n = 2; //you can set the amount of items you want to skip
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream
.skip(n) //skip the first n numbers
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
publicstaticvoidmain(字符串[]args){
字符串fileName=“/home/daniel/doc”;//文本文件位置
int n=2;//您可以设置要跳过的项目数量
try(Stream=Files.line(path.get(fileName))){
流动
.skip(n)//跳过前n个数字
.forEach(System.out::println);
}捕获(IOE异常){
e、 printStackTrace();
}
}
此处不需要流。如果该语言支持某些功能,那么使用streams/lambdas做任何事情都无关紧要。在Java8中,已经有了漂亮的文件
类来执行这些操作
public static List<String> getLines(String filePath) throws IOException {
Path file = Paths.get(filePath);
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
return new ArrayList<>(lines.subList(2, lines.size() - 1));
}
公共静态列表getLines(字符串文件路径)引发IOException{
Path file=Path.get(filePath);
列表行=Files.readAllLines(文件,StandardCharsets.UTF_8);
返回新的ArrayList(lines.subList(2,lines.size()-1));
}
您可以用更复杂的逻辑来代替硬编码索引来确定它
希望有帮助 您可以尝试以下代码段:
static boolean isPresent = false;
public static void main(String[] args) {
List<String> list =Stream.of("House","Tree","Pillow","Sky")
.filter((s)-> {
if(!isPresent){
isPresent=s.equals("Pillow");
}
return isPresent;
})
.collect(Collectors.toList());
System.out.println(list);
}
static boolean isPresent=false;
公共静态void main(字符串[]args){
列表=溪流(“房子”、“树”、“枕头”、“天空”)
.过滤器((s)->{
如果(!isPresent){
isPresent=s.equals(“枕头”);
}
返回iPresent;
})
.collect(Collectors.toList());
系统输出打印项次(列表);
}
现在,如果要使用正则表达式,可以执行以下操作
public static void main(String[] args) {
String fileName = "/home/daniel/Desktop/doc"; //text file location
String regex = "Pillow|Sky"; // add your regular expression here
Pattern p = Pattern.compile(regex);
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
List<String> filteredList = stream
.filter(str->p.matcher(str).matches())
.collect(Collectors.toList()); //collect items into a list
filteredList.stream().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
publicstaticvoidmain(字符串[]args){
字符串fileName=“/home/daniel/Desktop/doc”;//文本文件位置
String regex=“枕头|天空”//在此处添加正则表达式
Pattern p=Pattern.compile(regex);
try(Stream=Files.line(path.get(fileName))){
列表过滤器列表=流
.filter(str->p.matcher(str.matches())
.collect(Collectors.toList());//将项目收集到列表中
filteredList.stream().forEach(System.out::println);
}捕获(IOE异常){
e、 printStackTrace();
}
}
如果您想在匹配特定值后按打印行过滤流,可能流不是最好的方法。它不打算保持状态,您需要在此处保持状态(您是否已经达到该值)
您可以使用流和过滤器这样做:
public class MainClass {
public static void main(String[] args) {
System.out.println(new Date()+": Let's start our StackOverflow helper project!");
List<String> res= Arrays.asList("house","Tree","Pillow","Sky");
BooleanWrapper valueFound = new BooleanWrapper();
List<String> result = res.stream()
.filter(string -> valueFound.value || "Pillow".equals(string) && (valueFound.value = true))
.collect(Collectors.toList());
result.forEach(System.out::println);
}
}
class BooleanWrapper {
boolean value=false;
}
public类MainClass{
公共静态void main(字符串[]args){
System.out.println(new Date()+“:让我们开始我们的StackOverflow助手项目!”);
List res=Arrays.asList(“房子”、“树”、“枕头”、“天空”);
BooleanWrapper valueFound=新的BooleanWrapper();
列表结果=资源流()
.filter(字符串->valueFound.value | |“枕头”。等于(字符串)和&(valueFound.value=true))
.collect(Collectors.toList());
result.forEach(System.out::println);
}
}
类布尔包装器{
布尔值=假;
}
注意我们需要如何将布尔值包装到类中。如果我们只使用primitive,我们需要将其定义为final,以便在流中访问它,这意味着我们在找到它时无法将其更改为true
这也是一种黑客行为。它之所以有效,是因为我们在筛选器中最后一次执行赋值
valueFound.value=true
,并且只有在满足其他条件时才会发生。如果我们更改布尔测试的顺序,它将不起作用。您可以通过以下方法获得结果集:
public Set<String> getNames() throws IOException {
BufferedReader br;
FileInputStream inputStream = new FileInputStream("src/test/java/com/job/test.txt");
br = new BufferedReader(new InputStreamReader(inputStream));
String line;
List<String> fileStrings = new ArrayList<>();
while ((line = br.readLine()) != null){
fileStrings.add(line);
}
List<String> names = Arrays.asList("Pillow", "Sky");
return fileStrings.stream().filter(names::contains).collect(Collectors.toSet());
}
public Set getNames()引发IOException{
缓冲剂;
FileInputStream-inputStream=newfileinputstream(“src/test/java/com/job/test.txt”);
br=新的BufferedReader(新的InputStreamReader(inputStream));
弦线;
List fileStrings=new ArrayList();
而((line=br.readLine())!=null){
添加(第行);
}
列表名称=数组.asList(“枕头”、“天空”);
返回fileStrings.stream().filter(name::contains).collect(Collectors.toSet());
}
那么,您想开始保存列表中第三项(文本文件)的数据,还是使用某种正则表达式规则?到目前为止,您得到了什么?可能是@dsncode-yup的副本,正是如此。@dsncode-regular-expression我在发布我的答案时没有看到您的答案;)您的过滤条件更好,但我认为使用包装器类比使用静态变量更好。若您有两个线程,那个么静态变量可能会导致问题
public Set<String> getNames() throws IOException {
BufferedReader br;
FileInputStream inputStream = new FileInputStream("src/test/java/com/job/test.txt");
br = new BufferedReader(new InputStreamReader(inputStream));
String line;
List<String> fileStrings = new ArrayList<>();
while ((line = br.readLine()) != null){
fileStrings.add(line);
}
List<String> names = Arrays.asList("Pillow", "Sky");
return fileStrings.stream().filter(names::contains).collect(Collectors.toSet());
}