當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Scala Mutable SortedMap filterKeys()用法及代碼示例

filterKeys()方法用於查找所有鍵滿足給定謂詞的對。

Method Definition: def filterKeys(p:(A) => Boolean):SortedMap[A, B]

Return Type: It returns all the “key-value” pairs of the SortedMap where, the keys satisfies the given predicate.

範例1:

// Scala program of filterKeys() 
// method 
import scala.collection.SortedMap 
  
// Creating object 
object GfG 
{  
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating SortedMap 
        val m1 = SortedMap(5 -> "geeks", 4 -> "for", 2 -> "cs") 
          
        // Applying filterKeys method 
        val result = m1.filterKeys(_ > 2) 
          
        // Displays output 
        println(result) 
      
    } 
}
輸出:

Map(4 -> for, 5 -> geeks)

在此,僅返回兩個鍵值對,因為它們的鍵大於兩個大於指定謂詞的鍵對。
範例2:

// Scala program of filterKeys() 
// method 
import scala.collection.SortedMap 
  
// Creating object 
object GfG 
{  
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating SortedMap 
        val m1 = SortedMap(3 -> "geeks", 1 -> "for", 2 -> "cs") 
          
        // Applying filterKeys method 
        val result = m1.filterKeys(_ > 3) 
          
        // Displays output 
        println(result) 
      
    } 
}
輸出:
Map()

在此,沒有鍵對返回,因為沒有一個鍵滿足所陳述的謂詞。




相關用法


注:本文由純淨天空篩選整理自Shivam_k大神的英文原創作品 Scala Mutable SortedMap filterKeys() method with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。