仅保留文件中指定的最后[integer]行,其中包含提供的
嗨,我正在逐行读取字符串数组文件。传递参数以保留整数(即-k字符串,可选整数)。我只需要保留文件中包含Provide的最后[integer]行。预先感谢。
if(arguments.equals(“-k”)){
//read all lines in file
List<String> lines = Files.readAllLines(Paths.get(filename));
//keep phrase after -k
List<String> toKeep = Arrays.asList((args[i + 1]));
//New list string matchedLines sort file containing phrase -r
List<String> matchedLines = lines.stream().sorted()
.filter(e ->
(toRemove.stream().filter(d ->
e.contains(d)).count()) < 1)
.collect(Collectors.toList());
FILE =“ 1白色和黑色的狐狸\ r 2鸟是红色和黑色的鸟儿”;
String args [] = {“ -k”,“ i”,“ 1”,inputFile.getPath()};
预期输出: 2鸟是红色和黑色
答案 0 :(得分:0)
如果要在过滤后的匹配结果中保留最后n
个结果 ,则可以重新分配变量并使用Java 8流skip
方法:
// Collect list of strings that match -k
List<String> matchedLines = lines.parallelStream()
.sorted()
.filter(line -> toKeep.stream().anyMatch(line::contains))
.collect(Collectors.toList());
// Get only n matches
matchedLines = matchedLines.stream()
.skip(Math.max(0, matchedLines.size() - n))
.collect(Collectors.toList());
这会跳过前matchedLines.size() - n
行,其中n
是您要返回的行数。如果n
大于匹配的字符串数,例如matchedLines.size() - n < 0
,它将返回所有项目(跳过0)。