如何在 java 中定义相似的 lambda 函数(在一个函数中有所不同)

How to define lambda function that are similar (vary in one function) in java

我需要一些帮助。 我创建了一个功能接口,它有一个名为 filter:

的抽象方法
@FunctionalInterface
interface FileFilter {
    /**
     * This method gets a file path and filters it in some method.
     * @return a list of the remaining files after this filter.
     * @throws IOException
     */
    abstract boolean filter(Path path) throws IOException;
}

我需要创建此方法的几个不同实现,分为两组: 1.少数按不同文件大小过滤(以它们之间的差异为标准)。 2.一些按不同文件名过滤的。 (它们之间的唯一区别是 String 方法的单一选择 - contains / startsWith

当它们如此相似时,为它们中的每一个创建一个不同的函数来实现我的 filter 方法对我来说似乎很愚蠢,但我想不出一种方法来克服这个问题。 我想为每个组编写一个函数(returns 一个正确的 lambda)。

例如,现在从第二组创建过滤器的方法如下所示:

   static FileFilter prefixFilter(String[] parameters, int expectedLength) throws
            BadParameterFilterException{
        String value = parameters[0];
        if(doesContainNOTSuffix(parameters.length, expectedLength, parameters[parameters.length-1])){
            return path -> !(path.getFileName().toString().startsWith(value);
        }
        return path -> (path.getFileName().toString().startsWith(value);
    }

    /**
     * This class implements the suffix filter.
     * @param parameters given command paramaters.
     * @param expectedLength the expected length of the command with a NOT suffix.
     * @return lambda function of the greater_than filter.
     * @throws BadParameterFilterException
     */
    static FileFilter suffixFilter(String[] parameters, int expectedLength) throws
            BadParameterFilterException{
        String value = parameters[0];
        if(doesContainNOTSuffix(parameters.length, expectedLength, parameters[parameters.length-1])){
            return path -> !(path.getFileName().toString().endsWith(value);
        }
        return path -> (path.getFileName().toString().endsWith(value);
    }

它们仅在 lambda 中使用的 String 方法不同。 我想将它们合二为一,但你不能将方法作为变量传递。

谢谢!

只是为了将显示的两种方法合二为一,您可以添加另一个 BiPredicate<String, String> 参数。

static FileFilter stringFilter(String[] parameters, int expectedLength, BiPredicate<String, String> stringPredicate) throws
        BadParameterFilterException{
    String value = parameters[0];
    if(doesContainNOTSuffix(parameters.length, expectedLength, parameters[parameters.length-1])){
        return path -> !stringPredicate.test(path.getFileName().toString(), value);
    }
    return path -> stringPredicate.test(path.getFileName().toString(), value);
}

并在这两种情况下分别将(x, y) -> x.endsWith(y)(x, y) -> x.startsWith(y)传递给它。

对于文件大小谓词,您可能可以使用相同的方法来完成。