簡體   English   中英

如何使用Kotlin將列表轉換成地圖

[英]How to transform a list into a map with Kotlin

我正在嘗試從列表中構建地圖。 我的目標是比較兩個列表,並發現這兩個列表之間的差異。 然后,我想構造一個地圖,以便知道在哪個索引中發現了差異。

我用Java做到了這一點,雖然我認為不是很好,但是它正在工作。

//I compare the two values for a given index, if value are the same, I set null in my result list
List<String> result = IntStream.range(0, list1.size()).boxed()
                .map(i -> list1.get(i) != list2.get(i) ? (list1.get(i)  + " != "+ list2.get(i)) : null)
                .collect(Collectors.toList());

//I filter all the null values, in order to retrieve only the differences with their index
Map<Integer, String> mapResult =
            IntStream.range(0, result.size())
            .boxed().filter(i-> null != result.get(i))
            .collect(Collectors.toMap(i -> i,result::get));

這不是最佳選擇,但是可以正常工作。 如果您對這些代碼行有建議,我會很樂意接受。

我嘗試兩次在Kotlin中復制這種行為,但是我沒有成功使用map()構造函數。 (我仍在學習Kotlin,對此我不太熟悉)。

謝謝您的幫助。

您可以在集合中使用zip函數來連接兩個元素。 withIndex()函數有助於將一個列表變成元素索引和值對的列表。 完整的解決方案可能如下


    val list1 = listOf("a", "b", "c")
    val list2 = listOf("a", "B", "c")

    val diff : Map<Int, String> = list1.withIndex()
        .zip(list2) { (idx,a), b -> if (a != b) idx to "$a != $b" else null}
        .filterNotNull().toMap()

請注意,當兩個列表中都有元素時, zip函數將進行迭代,它將跳過任何列表中的剩余內容。 可以通過添加具有以下功能的空元素來解決此問題:


fun <T> List<T>.addNulls(element: T, toSize: Int) : List<T> {
    val elementsToAdd = (toSize - size)
    return if (elementsToAdd > 0) {
        this + List(elementsToAdd) { element }
    } else {
        this
    }
}

並在使用zip函數之前在兩個列表中都調用該函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM