0
can be expressed as
interface Set extends Predicate<Integer>
interface Set extends Predicate<Integer>
boolean contains(Set s, int i) { return s.test(i); }
interface Set extends Predicate<Integer>
boolean contains(Set s, int i) { return s.test(i); }
Set union(Set s, Set t) { return x -> contains(s, x) || contains(t, x); }
Set intersect(Set s, Set t) {return x -> contains(s, x) && contains(t, x);}
Set diff(Set s, Set t) { return x -> contains(s, x) && !contains(t, x); }
Set positive = x -> x > 0;
FileOutputStream file = new FileOutputStream("file.txt");
try {
file.write("Hello from past!".getBytes());
catch (Exception e) {
System.out.println("Something bad happened.");
e.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
} catch (Exception e) {}
}
}
try (FileOutputStream file = new FileOutputStream("file.txt")) {
file.write("Hello from present!".getBytes());
} catch (Exception e) {
System.out.println("Something bad happened.");
e.printStackTrace();
}
withResource(new FileOutputStream("file.txt"))
.perform(r -> r.write("Hello from better present!".getBytes()));
public class Resources {
public static <R> Action<R> withResource(final R r) {
return new Action<R>() {
@Override
public void perform(Consumer<R> consumer) {
try (AutoCloseable a = (AutoCloseable) r) {
R res = (R) a;
consumer.accept(res);
} catch (Exception e) {
System.out.println("Something bad happened.");
}
}
};
}
public static interface Consumer<T> {
void accept(T t) throws Exception;
}
public static interface Action<T> {
void perform (Consumer<T> consumer);
}
}
public class Main {
public static void main(String [] args) {
Predicate<Integer> p = x -> x > 0;
boolean res = p.test(1);
System.out.println(res);
}
}
javap -c Main
public static void main(java.lang.String[]);
Code:
0: invokedynamic #2, 0 // InvokeDynamic #0:test:()Ljava/util/function/Predicate;
5: astore_1
6: aload_1
7: iconst_1
8: invokestatic #3 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
11: invokeinterface #4, 2 // InterfaceMethod java/util/function/Predicate.test:(Ljava/lang/Object;)Z
16: istore_2
17: getstatic #5 // Field java/lang/System.out:Ljava/io/PrintStream;
20: iload_2
21: invokevirtual #6 // Method java/io/PrintStream.println:(Z)V
24: return
javap -p -c Main
private static boolean lambda$main$0(java.lang.Integer);
Code:
0: aload_0
1: invokevirtual #7 // Method java/lang/Integer.intValue:()I
4: ifle 11
7: iconst_1
8: goto 12
11: iconst_0
12: ireturn
public class Main2 {
public static void main(String [] args) {
doTest(x -> x > 0, 7);
doTest(Main2::test, 0);
}
public static boolean doTest(Predicate<Integer> p, int i) {
return p.test(i);
}
static boolean test(Integer x) { return x > 0; }
}
boolean test(Integer x) { return x > 0; }
Has type: Integer -> Boolean
“Don’t think, feel! It is like a finger pointing away to the moon. Don’t concentrate on the finger or you will miss all that heavenly glory.”
- Bruce Lee