I am trying to convert this java function to kotlin.
JavaScript
x
List<Long> creatorIds = polls.stream()
.map(Poll::getCreatedBy)
.distinct()
.collect(Collectors.toList());
List<User> creators = userRepository.findByIdIn(creatorIds);
Map<Long, User> creatorMap = creators.stream()
.collect(Collectors.toMap(User::getId, Function.identity()));
return creatorMap;
}
I end up with the following:
JavaScript
fun getPollCreatorMap(polls: List<Poll>): Map<Long?, User?>? {
// Get Poll Creator details of the given list of polls
val creatorIds: List<Long?> = polls.stream().collect(Collectors.toList())
.map(Poll::getCreatedBy).distinct()
val creators: List<User?>? = userRepository!!.findByIdIn(creatorIds)
val creatorMap: Map<Long?, User?> = creators!!.stream()
.collect(Collectors.toMap(User::getId, Function.identity()))
return creatorMap
}
However on the line
JavaScript
.collect(Collectors.toMap(User::getId, Function.identity()))
I get the following error:
JavaScript
Type mismatch.
Required:
((User?) → Long?)!
Found:
KFunction1<User, Long?>
Advertisement
Answer
You don’t need stream()
in kotlin. The collections classes in kotlin provides all methods you need. (e.g. map, distinct, toMap). Here is the kotlin way to write your function:
JavaScript
fun getPollCreatorMap(polls: List<Poll>): Map<Long?, User?>? = polls.map{it.createdBy}.distinct().let{ creatorIds ->
userRepository?.findByIdIn(creatorIds)?.map{
Pair(it.id,it)
}.toMap()
}
I don’t know the nullability of your data so I just leaves them all nullable. If you know the nullability, you should try to make the code as exact as possible.