Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
Kotlin groupby value as set instead of list

I'm going to groupby Set<Pair<String,Int>> values to Map<String, Set<Int>> so simply. Find all matching ints for string and create set. I've got solution that works:


setStringInt.stream()
            .collect(
                groupingBy(
                    Projection::stringObj,
                    mapping(Projection::intObj,
                        toSet<Int>())
                )
            )

I've got kind of cleaner:

            .groupBy { it.stringobj }
            .mapValues { it.value.map { it.intobj }.toSet() }

But it's looking quite dirty. Do you have any idea how to simplify this? Am I able to do this without using stream?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

I think this is more readable:

setStringInt.groupBy({ it.first }, { it.second }).mapValues { it.value.toSet() }

using the

inline fun <T, K, V> Iterable<T>.groupBy(
    keySelector: (T) -> K,
    valueTransform: (T) -> V
): Map<K, List<V>>

overload.

over 4 years ago · Santiago Trujillo Report

0

You can just use the Kotlin functions groupBy and then mapValues directly on the Set.

You first use groupBy on it.first to get a Map<String, List<Pair<String, Int>>. Then you need to map the values of the resulting map, so you get a List<Int> from the List<Pair<String, Int>>. Like this:

setStringInt.groupBy { it.first }
            .mapValues { entry -> entry.value.map { it.second }.toSet() }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!