如何解决使用StringBuilder的Stream.collect有效,但是Custom类不起作用
// 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","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","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)缺少某些东西
非常感谢您的帮助。
解决方法
将StringBuilder
方法的使用方式与Int2
方法的使用方式进行比较:
.collect(StringBuilder::new,StringBuilder::append,StringBuilder::append)
.collect(
() -> int2,int2::accumulator,int2::combiner)
很显然,它们的形式不同。 int2::accumulator
指称为accumulator
的特定Int2
实例上的int2
方法。 StringBuilder::append
是指append
方法。这些是不同类型的方法参考。有关各种方法引用的更多信息,请参见“方法引用的种类” in this page。
您应该改用:
.collect(
Int2::new,Int2::accumulator,Int2::combiner)
int2::accumulator
在文档中被称为“对特定对象的实例方法的引用”,它是指采用String
并返回void
的方法,因此可以将其传递到Consumer<String>
中。但是,collect
期望BiConsumer<Int2,String>
作为第二个参数。
因为Int2::accumulator
没有引用Int2
的特定实例。在文档中被称为“对特定类型的任意对象的实例方法的引用”。它代表一个函数,除了Int2
通常接受的其他参数之外,该函数还将accumulator
的实例作为其第一个参数。这就是为什么您可以传递Int2::accumulator
的原因。类似的解释可以应用于Int2::combiner
。
不用说,但是您的方法是空的,因此它在运行时不会做任何事情。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。