Java OCA OCP Practice Question 1953

Question

Assuming the directory /p1/p2 exists and its contents are accessible, which statement about the following code snippet is correct?.

Path p = Paths.get("/p1/p2"); 
  
Files.walk(p) /*  ww  w  . jav a2s  .  c  om*/
   .map(z -> z.toAbsolutePath().toString()) 
   .filter(s -> s.endsWith(".java")) 
   .collect(Collectors.toList()).forEach(System.out::println); 
  
Files.find(p,Integer.MAX_VALUE, 
      (w,a) -> w.toAbsolutePath().toString().endsWith(".java")) 
   .collect(Collectors.toList()).forEach(System.out::println); 
  • A. The first stream statement does not compile.
  • B. The second stream statement does not compile.
  • C. Both statements compile but are unlikely to print the same results at runtime.
  • D. None of the above


D.

Note

Both stream statements compile without issue, making Options A and B incorrect.

The two statements are equivalent to one another and print the same values at runtime.

Option C is incorrect, and Option D is correct.

There are some subtle differences in the implementation besides one using walk() with a filter() and the other using find().

The walk() call does not include a depth limit, but since Integer.MAX_VALUE is the default value, the two calls are equivalent.

Furthermore, the walk() statement prints a stream of absolute paths stored as String values, while the find() statement prints a stream of Path values.

If the input p was a relative path, then these two calls would have very different results, but since we are told p is an absolute path, the application of toAbsolutePath() does not change the results.




PreviousNext

Related