Available in versions: Dev (3.18) | Latest (3.17)

Kotlin MULTISET 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 MULTISET or MULTISET_AGG as follows:

val map: Field<Map<Int, String>> =
multisetAgg(LANGUAGE.ID, LANGUAGE.CD).convertFrom { r -> r.collect(Records.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> Field<Result<Record1<E>>>.intoArray(): Field<Array<E>> = collecting(Records.intoArray(E::class.java))
fun <K, V, R : Record2<K, V>> Field<Result<R>>.intoGroups(): Field<Map<K, List<V>>> = collecting(Records.intoGroups())
fun <E, R : Record1<E>> Field<Result<R>>.intoList(): Field<List<E>> = collecting(Records.intoList())
fun <K, V> Field<Result<Record2<K, V>>>.intoMap(): Field<Map<K, V>> = collecting(Records.intoMap())
fun <E, R : Record1<E>> Field<Result<R>>.intoSet(): Field<Set<E>> = collecting(Records.intoSet())

// [... and more]

This allows for the leaner version below:

val map: Field<Map<Int, String>> =
multisetAgg(LANGUAGE.ID, LANGUAGE.CD).intoMap()

Feedback

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

The jOOQ Logo