Available in versions: Dev (3.18)

This documentation is for the unreleased development version of jOOQ. Click on the above version links to get this documentation for a supported version of jOOQ.

Kotlin ResultQuery Collectors

Applies to ✅ Open Source Edition   ✅ Express Edition   ✅ Professional Edition   ✅ Enterprise Edition

jOOQ's runtime API implements a few useful Collectors that can be used to fetch data into a map, for example:

public class Records {

    // [...]
    
    public static final <K, V, R extends Record2<K, V>> Collector<R, ?, Map<K, V>> intoMap() {
        return intoMap(Record2::value1, Record2::value2);
    }
    
    // [...]
    
}

These can be used with the collect() method as follows:

val map: Map<Int, String> =
create.select(LANGUAGE.ID, LANGUAGE.CD)
      .from(LANGUAGE)
      .collect(intoMap())

The Collector leverages the query's type safety, such that it works only for queries projecting exactly 2 columns. Using the kotlin extensions module, a few useful extension functions are made available as follows:

package org.jooq.kotlin

inline fun <reified E> ResultQuery<Record1<E>>.fetchArray(): Array<E> = collect(Records.intoArray(E::class.java))
fun <K, V, R : Record2<K, V>> ResultQuery<R>.fetchGroups(): Map<K, List<V>> = collect(Records.intoGroups())
fun <E, R : Record1<E>> ResultQuery<R>.fetchList(): List<E> = collect(Records.intoList())
fun <K, V> ResultQuery<Record2<K, V>>.fetchMap(): Map<K, V> = collect(Records.intoMap())
fun <E, R : Record1<E>> ResultQuery<R>.fetchSet(): Set<E> = collect(Records.intoSet())

This allows for the leaner version below:

val map: Map<Int, String> =
create.select(LANGUAGE.ID, LANGUAGE.CD)
      .from(LANGUAGE)
      .fetchMap()

Feedback

Do you have any feedback about this page? We'd love to hear it!

The jOOQ Logo