猿问

Java 8流多个过滤器

我是Java 8的新手,正在尝试对Streams的需求。我有一个包含数千个Recod的csv文件,我的csv格式是


DepId,GrpId,EmpId,DepLocation,NoofEmployees,EmpType

===

D100,CB,244340,美国,1000,合同

D101,CB,543126,美国,1900,永久

D101,CB,356147,美国,1800,合同

D100,DB,244896,HK,500,半合约

D100,DB,543378,HK,100,永久

我的要求是使用两个条件过滤记录:a)EmpId以“ 244”开头或EmpId以“ 543”开头b)EmpType是“ Contract”和“ Permanent”


我在下面尝试


 try (Stream<String> stream = Files.lines(Paths.get(fileAbsolutePath))) {

    list = stream                

        .filter(line -> line.contains("244") || line.contains("543"))

        .collect(Collectors.toList());

     }

它正在基于244和543过滤员工,但是我担心的是,因为我使用的包含它可能还会获取其他数据,即它将不仅从EmpId列而且还会从其他列获取数据(其他列可能也包含以开头的数据这些数字)


类似地,因为我正在逐行阅读中合并EmpType,所以我没有办法强制将EmpType设置为“ Permanent”和“ Contract”


我是否缺少任何高级选项?


明月笑刀无情
浏览 184回答 2
2回答

一只甜甜圈

你可以这样做Pattern comma = Pattern.compile(",");Pattern empNum = Pattern.compile("(244|543)\\d+");Pattern empType = Pattern.compile("(Contract|Permanent)");try (Stream<String> stream = Files.lines(Paths.get("C:\\data\\sample.txt"))) {&nbsp; &nbsp; List<String> result = stream.skip(2).map(l -> comma.split(l))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(s -> empNum.matcher(s[2]).matches())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(s -> empType.matcher(s[5]).matches())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(s -> Arrays.stream(s).collect(Collectors.joining(",")))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());&nbsp; &nbsp; System.out.println(result);} catch (IOException e) {&nbsp; &nbsp; e.printStackTrace();}首先读取文件,并跳过2个标题行。然后使用,字符将其拆分。使用EmpId和过滤掉它EmpType。接下来,再次合并令牌以形成行,最后将每行收集到中List。

慕容森

优雅的方式是正则表达式,我现在将略过。使用Stream API的不太优雅的方法如下:list = stream.filter(line -> {&nbsp; &nbsp; String empId = line.split(",")[2];&nbsp; &nbsp; return empId.startsWith("244") || empId.startsWith("543");}.collect(Collectors.toList());使用Stream API(由shmosel指出)的较短方法是使用迷你正则表达式。list = stream.filter(line -> line.split(",")[2].matches("(244|543).*")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toList());
随时随地看视频慕课网APP

相关分类

Java
我要回答