java 如何通过将数组的第一个元素转换为 String 从 List<Object[]> 获取 List<String>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34932230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:33:49  来源:igfitidea点击:

How to get List<String> from List<Object[]> by converting first element of array to String

javajava-8

提问by teja1905

How to get List<String>from List<Object[]>by converting the first element of array to String?

如何获得List<String>List<Object[]>由数组的第一个元素转换为字符串?

I tried writing like below but casting is not happening,

我尝试像下面这样写,但没有发生铸造,

List<String> results = query.getResultList()
.stream()
.map(result ->{
 Object[]  temp =  (Object[]) result;
 return temp[0].toString();
})
.collect(Collectors.toList());

Below image shows type of results list enter image description hereI am getting Error:java: incompatible types: java.lang.Object cannot be converted to java.util.List. How to do this correctly using Java 8?

下图显示了在此处输入图片说明我收到的结果列表类型 错误:java:不兼容的类型:java.lang.Object 无法转换为 java.util.List。如何使用 Java 8 正确执行此操作?

回答by Mrinal

query.getResultList()returns raw List. As mentioned by @Makoto in comment, try to use type-safe API. But if you intend to use the current API, add type casting (which will generate warning though).

query.getResultList()返回原始列表。正如@Makoto 在评论中提到的,尝试使用类型安全的 API。但是,如果您打算使用当前的 API,请添加类型转换(尽管会生成警告)。

List<String> results = ((List<Object[]>) query.getResultList())
.stream()
.map(result -> result[0].toString())
.collect(Collectors.toList());