【发布时间】:2014-10-21 18:12:35
【问题描述】:
我希望能够将任何 List 转换为 Object[] 的列表 - 即给定列表的每个元素都应该以给定的方式转换为 Object 数组。
例如,我有
List<User> users =
Lists.newArrayList(new User((long) 1, "Name1"), new User ((long) 2, "Name2"));
还有一个函数
Function <User, Object[]> mapper =
user -> new Object[] {user.getUserId(), user.getUserName()}
我需要通过使用映射器转换每个用户来获取对象数组列表。但重点是编写函数,它可以与任何给定的列表和任何给定的映射器一起工作。
我创建了 Transformer 类并尝试通过下一个方式实现我的目标,但出现编译错误:
class Transformer {
private List<?> content;
private Function<?, Object[]> mapper;
//getters and setters
....
public List<Object[]> transform() {
return content.stream()
.map(mapper) // this row isn't compiled
.collect(Collectors.toList());
}
}
Error:(75, 45) java: method map in interface java.util.stream.Stream<T> cannot be applied to given types;
required: java.util.function.Function<? super capture#1 of ?,? extends R>
found: java.util.function.Function<capture#2 of ?,java.lang.Object[]>
reason: cannot infer type-variable(s) R
(argument mismatch; java.util.function.Function<capture#2 of ?,java.lang.Object[]> cannot be converted to java.util.function.Function<? super capture#1 of ?,? extends R>)
你能给我什么建议?
【问题讨论】:
-
你遇到了什么错误?
-
错误:(75, 45) java: 接口 java.util.stream.Stream
中的方法映射不能应用于给定类型;必需:java.util.function.Function 找到:java.util.function.Function 原因:无法推断类型变量 R(参数不匹配;java.util.function.Function 无法转换为 java.util.function.Function super capture#1 of ?,? extends R>) -
@funny-funny 不要将此作为评论发布。此信息与问题相关,因此您应该edit 并在其中包含此信息。
-
@funny-funny 干得好。现在考虑以您得到的形式发布它,该格式很可能以易于阅读的方式进行格式化,而不是文字墙。
-
无论如何我怀疑你需要一种像
public static <T> List<Object[]> transform(List<T> content, Function <T, Object[]> mapper) {...}这样的方法,而不是单独的Transformer类。或者,如果您真的需要单独的类,则使用List<T> content和Function<T, Object[]> mapper字段将其设为通用class Transformer<T>{...}。
标签: java collections java-8