4

This is a code snippet that tries to use a functional interface inside the filter function.

Function<Path, Boolean> isNotPartitionFile = (path) -> {
    return !path.toString().contains("partition");
};

List<Path> pathsList =  Files.walk(Paths.get(extractFilesLocation))
                                 .filter(Files::isRegularFile)
                                 .filter(isNotPartitionFile)
                                 .collect(Collectors.toList());

When I try to use the isNotPartitionFile as a parameter to the filter() function, eclipse pops up an error that says The method filter(Predicate<? super Path>) in the type Stream<Path> is not applicable for the arguments (Function<Path,Boolean>). It also suggests to cast to (Predicate<? super Path>) , but this throws a runtime error that says it cannot be casted. How do I overcome this ?

kaushalpranav
  • 1,725
  • 24
  • 39

4 Answers4

2

isNotPartitionFile should be defined as:

Predicate<Path> isNotPartitionFile = path -> !path.toString().contains("partition");

because filter consumes a Predicate<T> not Function<T, R>.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
1

Predicate is a function that takes in a value and always return boolean. .filter is expecting a Predicate<T> and not a Function<T, Boolean>. The reason Predicate<T> doesn't extend Function<T, Boolean> is because Predicate<T> returns boolean which can never be null. To fix your issue, you could change your isNotPartitionFile to

Predicate<Path> isNotPartitionFile = (path) -> path.toString().contains("partition");
StaticBeagle
  • 5,070
  • 2
  • 23
  • 34
1

I figured out the solution myself.

The filter function expects a function as a parameter, but a functional interface was passed. So it needs to be replaced with the apply function of the Function interface.

List<Path> pathsList =  Files.walk(Paths.get(extractFilesLocation))
                                 .filter(Files::isRegularFile)
                                 .filter(isNotPartitionFile::apply)
                                 .collect(Collectors.toList());
kaushalpranav
  • 1,725
  • 24
  • 39
1

Stream<T> filter(Predicate<? super T> predicate) apply Predicate as parameter.

Predicate is a boolean-valued function.

Try this:

Predicate<Path> isNotPartitionFile = path -> !path.toString().contains("partition");
Maxim Kasyanov
  • 938
  • 5
  • 14