public static void main(String[] args) {
IntStream isa = IntStream.range(1, 101);
IntStream isb = IntStream.rangeClosed(1, 100);
System.out.println(isa.sum());
System.out.println(isb.sum());
Stream<Integer> is = Stream.of(1, 2, 3, 4, 5, 6, 7, 8);
//is.forEach(System.out::print);
is.filter(e -> e % 2 == 0).forEach(e -> System.out.printf("%d ", e));
System.out.println();
System.out.println("=============");
List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println(list);
Stream<Integer> s1 = list.stream();
s1.forEach(e -> System.out.printf("%2d ", e));
System.out.println();
//并行流
Stream<Integer> s2 = list.parallelStream();
s2.forEach(e -> System.out.printf("%2d ", e));
System.out.println("当前线程数" + Thread.activeCount());
IntStream aa = Arrays.stream(new int[]{
1, 2, 3, 4, 5, 6, 7, 8, 9}).parallel();
aa.forEach(e -> System.out.printf("%2d ", e));
System.out.println("当前线程数" + Thread.activeCount());
//生成4个数,从1开始,依次加3
Stream<Integer> ss1 = Stream.iterate(1, x -> x + 3).limit(4);
ss1.forEach(e -> System.out.printf("%2d ", e));
System.out.println();
//生成10个随机小数
Stream<Double> ss2 = Stream.generate(Math::random).limit(10);
ss2.forEach(e -> System.out.printf("%.3f ", e));
System.out.println();
Random r = new Random();
IntStream ss3 = IntStream.generate(() -> r.nextInt(1, 101)).limit(10);
ss3.forEach(e -> System.out.printf("%2d ", e));
System.out.println();
IntStream ss4 = IntStream.generate(() -> {
Random rand = new Random();
return rand.nextInt(1, 101);
}).limit(10);
ss4.forEach(e -> System.out.printf("%2d ", e));
System.out.println();
}
public static void main(String[] args) {
//过滤
IntStream ss1 = IntStream.range(1, 10);
ss1.map(e -> e * e).forEach(e -> System.out.printf("%02d ", e));
Stream<StudentA1> ss = Stream.of(
new StudentA1(1, "张三", 58, "男"),
new StudentA1(2, "张斯", 62, "男"),
new StudentA1(3, "张当", 45, "女"),
new StudentA1(4, "李书", 98, "男")
);
//Set<StudentA1> s1 = ss.collect(Collectors.toSet());
//System.out.println(s1);
//List<StudentA1> list = ss.toList();
//List<String> listname = ss.map(StudentA1::getName).toList();
//System.out.println(listname);
System.out.println();
int[] nn = {
1, 2, 3, 4, 5};
int sumnn = Arrays.stream(nn).sum();
System.out.println(sumnn);
//过滤
ss.filter(e -> e.getSex().contains("男")).forEach(System.out::println);
}
}
可以将list,set,自定义的当成Stream流进行处理。
开启多线程的3种方法
继承Thread类,重写run方法
class T1 extends Thread {
@Override
public void run() {
System.out.println("hello t1");
}
}
使用
var t1 = new T1();
t1.start();
实现Runnable接口 实现run方法,对象作为Thread的参数
var t2 = new Thread(() -> {
System.out.println("hello t2");
}, "t2");
t2.start();
实现Callable接口,对象作为Thread的参数,此方法的多线程主要是用来返回值的。
Callable<Integer> call = () -> {
System.out.println("hello t3 返回10");
return 10;
};
FutureTask<Integer> ft = new FutureTask<>(call);
var t3 = new Thread(ft);
t3.start();
System.out.println(ft.get());