用例
我目前在许多适配器中都有这种模式:
entries.stream()
.filter(Entry.class::isInstance)
.map(Entry.class::cast)
.map(Entry::getFooBar)
.collect(Collectors.toList());
其中条目是实现特定接口的对象的List
。不幸的是,接口--它是第三方库的一部分--没有定义通用的getter。要创建我想要的对象的列表,我需要搜索它们,转换它们,并调用适当的getter方法。
我打算将它重构为这样一个助手类:
public static <T, O> List<O> entriesToBeans(List<T> entries,
Class<T> entryClass, Supplier<O> supplier) {
return entries.stream()
.filter(entryClass::isInstance)
.map(entryClass::cast)
.map(supplier) // <- This line is invalid
.collect(Collectors.toList());
}
然后,我将调用此方法来执行转换:
Helper.entriesToBeans(entries,
Entry_7Bean.class,
Entry_7Bean::getFooBar);
不幸的是,我不能将getter传递到重构函数并让map调用它,因为map
需要一个函数。
问题
发布于 2015-03-12 16:40:03
一种类似于:
class T {
public O get() { return new O(); }
}
将映射到一个Function<T, O>
。
因此,只需将方法签名更改为:
public static <T, O> List<O> entriesToBeans(List<T> entries,
Class<T> entryClass, Function<T, O> converter) {
Update:我怀疑转换的原因是原始列表可能包含不属于Ts的元素。因此,您还可以将签名更改为:
public static <T, O> List<O> entriesToBeans(List<?> entries,
Class<T> entryClass, Function<T, O> converter) {
例如,您可以传递一个List<Object>
,并且只将Ts保存在列表、强制转换和转换中。
作为参考,下面是一个工作示例(打印John, Fred
):
static class Person {
private final String name;
Person(String name) { this.name = name; }
String name() { return name; }
}
public static void main(String[] args) {
List<String> result = entriesToBeans(Arrays.asList(new Person("John"), new Person("Fred")),
Person.class, Person::name);
System.out.println("result = " + result);
}
public static <T, O> List<O> entriesToBeans(List<?> entries,
Class<T> entryClass, Function<T, O> converter) {
return entries.stream()
.filter(entryClass::isInstance)
.map(entryClass::cast)
.map(converter)
.collect(Collectors.toList());
}
发布于 2015-03-12 16:40:42
您应该传递一个Function<T, O>
,而不是:
public static <T, O> List<O> entriesToBeans(List<T> entries, Class<T> entryClass,
Function<T, O> mapper) {
return entries.stream().filter(entryClass::isInstance)
.map(entryClass::cast).map(mapper)
.collect(Collectors.toList());
}
https://stackoverflow.com/questions/29015397
复制相似问题