Reputation: 1447
I know how to get a list of attributes from an object list into a new list.
But how about if I also want to convert the type from int
to long
. For example, if I have a user class with a method called get userId (which is int
type) and myUserList
is a list of user objects.
List<Integer> userIdList = myUserList.stream()
.map(User::getUserId)
.collect(Collectors.toList());
So I could get a list of userId with int
type. How about if I want to convert int
to long
. I tried this code:
myUserList.stream()
.map(Long::intValue(User::getUserId))
.collect(Collectors.toList());
I had an error can not resolve method static...
.
May anyone tell me how to fix it?
Upvotes: 1
Views: 103
Reputation: 59212
You can convert an int to a long by casting
.map(user -> (long) user.getUserId())
or (since it needs to be boxed anyway to go into a list), you can use Long.valueOf
.
userList.stream()
.map(user -> Long.valueOf(user.getUserId()))
.collect(Collectors.toList());
Upvotes: 4