forked from usf-cs272-fall2022/lectures
/
PathMatcherDemo.java
83 lines (69 loc) · 2.57 KB
/
PathMatcherDemo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package edu.usfca.cs272;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.util.function.Predicate;
/**
* Demonstrates lambda expressions using the {@link PathMatcher} functional
* interface.
*
* @author CS 272 Software Development (University of San Francisco)
* @version Fall 2022
*/
public class PathMatcherDemo {
/**
* Demonstrates the examples in the lambda expression lecture slides.
*
* @param args unused
*/
public static void main(String[] args) {
Path hello = Path.of("hello.txt");
Path world = Path.of("txt.world");
// anonymous inner class
PathMatcher anonClass = new PathMatcher() {
@Override
public boolean matches(Path p) {
return p.toString().endsWith(".txt");
}
};
System.out.println(hello + ": " + anonClass.matches(hello));
System.out.println(world + ": " + anonClass.matches(world));
System.out.println();
// verbose lambda expression
PathMatcher verboseLambda = (Path p) -> {
return p.toString().endsWith(".txt");
};
System.out.println(hello + ": " + verboseLambda.matches(hello));
System.out.println(world + ": " + verboseLambda.matches(world));
System.out.println();
// compact lambda expression
PathMatcher compactLambda = p -> p.toString().endsWith(".txt");
System.out.println(hello + ": " + compactLambda.matches(hello));
System.out.println(world + ": " + compactLambda.matches(world));
System.out.println();
// changing the identifier type
// only the function "shape" matters (not the name)
Predicate<Path> predicateLambda = p -> p.toString().endsWith(".txt");
System.out.println(hello + ": " + predicateLambda.test(hello));
System.out.println(world + ": " + predicateLambda.test(world));
System.out.println();
// can the var keyword be used for anonymous inner classes?
// yes, the type is given by the constructor call
var varAnonClass = new PathMatcher() {
@Override
public boolean matches(Path p) {
return p.toString().endsWith(".txt");
}
};
System.out.println(hello + ": " + varAnonClass.matches(hello));
System.out.println(world + ": " + varAnonClass.matches(world));
System.out.println();
// can the var keyword be used for lambda expressions?
// no, lambda expressions have no standalone type and require a target type
// https://stackoverflow.com/questions/49578553/why-cant-the-var-keyword-in-java-be-assigned-a-lambda-expression
// var varLambda = p -> p.toString().endsWith(".txt");
//
// System.out.println(hello + ": " + varLambda.test(hello));
// System.out.println(world + ": " + varLambda.test(world));
// System.out.println();
}
}