在Java 8中使用map函数类型转换不起作用 [英] Type cast not working using map function in Java 8

查看:542
本文介绍了在Java 8中使用map函数类型转换不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在比较两个列表。

 列出allUserGroups = UserBC.getAllGroupsForUser(userId,deptID); 
列表< String> confUserGroups = Arrays.asList(configuredSet);

列表1返回Object,我需要对GroupData实体进行类型转换。 GroupData有多个字段,并希望比较其中一个字段'id'。所以我使用map函数来进行类型转换,如下所示:

  isValuePresent = allUserGroups.stream()。map(p  - >(GroupData )p).anyMatch(p  - > confUserGroups.contains(p.getId())); 

问题在于,对于 p.getId()它再次要求强制转换。编译器要求再次添加强制转换。任何人都可以请建议,如果我错过了什么。



EDIT1:
id是long类型,否则我可以使用



EDIT2:代码由Joop回答,但得到同样的错误



  allUserGroups.stream()解决方案

.map(GroupData.class :: cast)
.map(GroupData :: getID)
.anyMatch(confUserGroups.contains)

例如字符串 class:

 列表与LT;对象> list = Arrays.asList(a,ab,abc); 
list.stream()
.map(String.class :: cast)//转换为字符串
.map(String :: getBytes)//对每个元素调用getBytes
.forEach(System.out :: println);


I am comparing two lists.

List allUserGroups = UserBC.getAllGroupsForUser(userId, deptID);
List<String> confUserGroups= Arrays.asList(configuredSet);

List one returns Object which I need to typecast to GroupData entity. GroupData has multiple fields and want to compare for one of the fields 'id'. So I used map function to typecast as below,

isValuePresent = allUserGroups.stream().map(p -> (GroupData) p).anyMatch(p -> confUserGroups.contains(p.getId()));

Issue is, for p.getId() its again asking for typecast. Compiler asks to add cast again. Can anyone please suggest if I missed anything.

EDIT1: id is of long type otherwise I could have used ((GroupData)p).getId()

EDIT2: Modified the code as answered by Joop, but getting same error

解决方案

You might try to use something like this:

allUserGroups.stream()
    .map(GroupData.class::cast)
    .map(GroupData::getID)
    .anyMatch(confUserGroups.contains)

for example with String class:

List<Object> list = Arrays.asList("a","ab","abc");
list.stream()
        .map(String.class::cast) // cast to String
        .map(String::getBytes) // call getBytes on every element
        .forEach(System.out::println); 

这篇关于在Java 8中使用map函数类型转换不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆