Create SortedMap with Comparator and items

KT-34142
This commit is contained in:
Valeriy.Vyrva
2019-10-02 17:52:05 +03:00
committed by Ilya Gorbunov
parent e3fb74b656
commit c023a02884
4 changed files with 29 additions and 0 deletions
@@ -113,6 +113,18 @@ public fun <K, V> Map<out K, V>.toSortedMap(comparator: Comparator<in K>): Sorte
public fun <K : Comparable<K>, V> sortedMapOf(vararg pairs: Pair<K, V>): SortedMap<K, V> =
TreeMap<K, V>().apply { putAll(pairs) }
/**
* Returns a new [SortedMap] with the specified contents, given as a list of pairs
* where the first value is the key and the second is the value.
*
* The resulting [SortedMap] determines the equality and order of keys according to the sorting order provided by the given [comparator].
*
* @sample samples.collections.Maps.Instantiation.sortedMapWithComparatorFromPairs
*/
@SinceKotlin("1.4")
public fun <K, V> sortedMapOf(comparator: Comparator<in K>, vararg pairs: Pair<K, V>): SortedMap<K, V> =
TreeMap<K, V>(comparator).apply { putAll(pairs) }
/**
* Converts this [Map] to a [Properties] object.
@@ -18,6 +18,15 @@ class MapJVMTest {
assertEquals(listOf("a", "b", "c"), map.keys.toList())
}
@Test fun createSortedMapWithComparator() {
val map = sortedMapOf(compareBy<String> { it.length }.thenBy { it }, Pair("c", 3), Pair("bc", 2), Pair("bd", 4), Pair("abc", 1))
assertEquals(1, map["abc"])
assertEquals(2, map["bc"])
assertEquals(3, map["c"])
assertEquals(4, map["bd"])
assertEquals(listOf("c", "bc", "bd", "abc"), map.keys.toList())
}
@Test fun toSortedMap() {
val map = mapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1))
val sorted = map.toSortedMap()
@@ -43,6 +43,13 @@ class Maps {
assertPrints(map.values, "[2, 3, 1]")
}
@Sample
fun sortedMapWithComparatorFromPairs() {
val map = sortedMapOf(compareBy<String> { it.length }.thenBy { it }, Pair("abc", 1), Pair("c", 3), Pair("bd", 4), Pair("bc", 2))
assertPrints(map.keys, "[c, bc, bd, abc]")
assertPrints(map.values, "[3, 2, 4, 1]")
}
@Sample
fun emptyReadOnlyMap() {
val map = emptyMap<String, Int>()
@@ -2445,6 +2445,7 @@ public final class kotlin/collections/MapsKt {
public static final fun putAll (Ljava/util/Map;Ljava/lang/Iterable;)V
public static final fun putAll (Ljava/util/Map;Lkotlin/sequences/Sequence;)V
public static final fun putAll (Ljava/util/Map;[Lkotlin/Pair;)V
public static final fun sortedMapOf (Ljava/util/Comparator;[Lkotlin/Pair;)Ljava/util/SortedMap;
public static final fun sortedMapOf ([Lkotlin/Pair;)Ljava/util/SortedMap;
public static final fun toList (Ljava/util/Map;)Ljava/util/List;
public static final fun toMap (Ljava/lang/Iterable;)Ljava/util/Map;