Skip to content
Advertisement

Getting a map and collectors error in kotlin function

I am trying to convert this java function to kotlin.

        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:

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

.collect(Collectors.toMap(User::getId, Function.identity()))

I get the following error:

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:

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement