[Java] Stream.collect(,,)

Stream 中的成员方法

<R> R collect(Supplier<R> supplier,
                  BiConsumer<R, ? super T> accumulator,
                  BiConsumer<R, R> combiner)

以及对应各种基本类型流的成员方法(比如int的)

<R> R collect(Supplier<R> supplier,
                  ObjIntConsumer<R> accumulator,
                  BiConsumer<R, R> combiner)

其中 supplier 用于提供集合,比如以下两种方式均可用作 supplier;

ArrayList<T>::new;
()->list;// list 为事先声明的集合

accumulator 用于将把 Stream 中的对象加入到集合中(用例:List::add)

combiner 用于并行处理,只有 Stream 是允许并行的(调用parallel())才起作用

对于并行流,这个方法会把流的对象加入多个集合中,最后根据情况把这些集合中的对象添加到 supplier 所提供的集合中(用例:List::addAll)

[Java] 基本类型运算返回类型

a θ b

  • θ为+、-、*、/等涉及数字运算的运算符
  • 返回a,b两者中最大的类型,如果这个类型小于int(byte、short、char)则返回int

x ? a : b

  • 如果两者类型一样则返回这个类型
  • 如果不一样,返回最大的类型,另外如果这个类型小于long
    • 如果其中一个类型为int,则优先返回另一个类型
    • 如果其中一个类型为char,则返回int

[Java] annotationType()和getClass() 在 Java 11 中的区别

先自己写个注解:

@Retention(RUNTIME)
public @interface TestAnno {
	String value() default "nul";
}

再进行测试:

@TestAnno
public class Test {
	public static void main(String[] args) throws Exception {
		var a = Test.class.getAnnotation(TestAnno.class);	
		
		var intr = a.annotationType();
		var im = intr.getMethod("value");
		System.out.println(im.invoke(a));
		
		var proxy = a.getClass();
		var pm = proxy.getMethod("value");
		System.out.println(pm.invoke(a));
	}
}

输出结果如下:

nul
Exception in thread "main" java.lang.IllegalAccessException: class info.tozzger.test.Test (in module info.tozzger.test) cannot access class com.sun.proxy.jdk.proxy1.$Proxy1 (in module jdk.proxy1) because module jdk.proxy1 does not export com.sun.proxy.jdk.proxy1 to module info.tozzger.test
	at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:361)
	at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:591)
	at java.base/java.lang.reflect.Method.invoke(Method.java:558)
	at info.tozzger.test/info.tozzger.test.Test.main(Test.java:14)

因此,在高版本的 JDK 中,应该使用 annotationType() 对注解进行操作。