import java.util.function.Consumer;
import java.util.function.IntConsumer;
public class ConsumerTest {
public void test(Consumer<Integer> consumer) {
consumer.accept(100);
}
public static void main(String[] args) {
ConsumerTest consumerTest = new ConsumerTest();
Consumer<Integer> consumer = i -> System.out.println(i);
IntConsumer intConsumer = i -> System.out.println(i);
System.out.println(consumer instanceof Consumer);
System.out.println(intConsumer instanceof IntConsumer);
consumerTest.test(consumer); // 面向对象方式
consumerTest.test(consumer::accept); // 函数式方式
consumerTest.test(intConsumer::accept); // 函数式方式
// consumerTest.test(intConsumer);
}
}
public class LambdaTest {
Runnable r1 = () -> System.out.println(this);
Runnable r2 = new Runnable() {
@Override
public void run() {
System.out.println(this);
}
};
public static void main(String[] args) {
LambdaTest lambdaTest = new LambdaTest();
Thread t1 = new Thread(lambdaTest.r1);
t1.start();
Thread t2 = new Thread(lambdaTest.r2);
t2.start();
}
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class StreamTest {
public static void main(String[] args) {
List<String> list = Arrays.asList("hello", "world", "hello world");
// 讲解Stream<T>与BaseStream<T, S extends BaseStream<T, S>>之间的继承关系
// NullPointerException nullPointerException = new NullPointerException("my exception");
// 如果不执行流的close方法,那么onClose的回调是不会执行的
try (Stream<String> stream = list.stream()) {
stream.onClose(() -> {
System.out.println("aaaa");
// throw new NullPointerException("first exception");
}).onClose(() -> {
System.out.println("bbbb");
// throw new ArithmeticException("second exception");
}).forEach(System.out::println);
}
}
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class StreamTest2 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
System.out.println(list.getClass());
// list.stream().map(i -> 2 * i).forEach(System.out::println);
Stream<Integer> stream = list.stream();
System.out.println(stream.getClass());
Stream stream2 = stream.map(i -> 2 * i);
System.out.println(stream2.getClass());
System.out.println("--------");
stream2.forEach(System.out::println);
// list.stream().parallel().forEach(System.out::println);
}
}