// S#1. stream works with StringBuilder
System.out.println(
Stream.of("a", "b", "c", "d", "ef", "ghi", "j")
.collect(StringBuilder::new,
StringBuilder::append,
StringBuilder::append)
.toString()
);
// S#2. stream works fine with Int
// my custom class that conforms to arg types of collect method
// method signature: collect(Supplier, accumulator, combiner)
Int anInt = new Int();
System.out.println(
Stream.of("a", "b", "c", "d", "ef", "ghi", "j")
.collect(() -> anInt, Int::accumulator, Int::combiner)
.total
);
class Int {
int total;
static void accumulator(Int result, String str) { result.total += str.length(); }
static void combiner(Int a, Int b) { a.total += b.total; }
}
// S#3. compiler error with Int2
// custom class I created which has method accumulator(String) similar to StringBuidler append(String)
// StringBuilder::append (used as above in S#1)
Int2 int2 = new Int2();
System.out.println(
Stream.of("a", "b", "c", "d", "ef", "ghi", "j")
.collect(() -> int2, int2::accumulator, int2::combiner)
);
class Int2 {
void accumulator(String s) {}
void combiner(Int2 b) {}
}
但是我想知道stringbuilder版本的代码是如何编译的,而s#3(int2版本)却没有。stringbuilder扩展自charsequence、abstractstringbuilder类。是不是因为我的自定义类(int2)中缺少的这种层次关系才起作用
非常感谢你的帮助。
1条答案
按热度按时间um6iljoc1#
比较您使用
StringBuilder
方法,以及你使用Int2
方法:显然,它们有不同的形式。
int2::accumulator
指accumulator
方法的特定示例Int2
打电话int2
.StringBuilder::append
但是,指append
方法。这些是不同类型的方法引用。有关不同类型的方法引用的详细信息,请参阅本页中的“各种方法引用”。您应该使用: