我有以下界面:
@FunctionalInterface
interface Mapper<I, O> {
Collection<O> map(I in);
}
计划按以下方式使用:
class Writer<E> {
private final Iterator<?> it;
private final Mapper<?, E> mapper;
private final Output<E> out;
public <T> Writer(Iterator<T> it, Mapper<T, E> mapper, Output<E> out) {
this.it = it;
this.mapper = mapper;
this.out = out;
}
void write() {
while (it.hasNext()) {
Collection<E> items = mapper.map(it.next());
for (E item : items) {
out.write(item);
}
}
}
}
问题是Writer类的用户必须将每个映射值装箱到一个集合中,即使他们想返回一个值也是如此。例如:
List<String> strings = Arrays.asList("a", "b", "c");
Writer<String> writer = new Writer<>(
strings.iterator(),
str -> Collections.singletonList(str),
new FileOutput(...));
用户必须写str -> Collections.singletonList(str)
而不是Function.identity()
(例如,构造函数引用StringHolder::new
)
是否有任何关于如何简化此方法的想法,或者这个问题是人为造成的?
谢谢!