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


Scala Map retain()用法及代碼示例


retain()方法用於保留滿足指定條件的所有Map對。

函數定義: def retain(p: (A, B) => Boolean): Map.this.type

返回類型: It returns all the “key-value” pairs of the map which satisfies the stated predicate.



範例1:

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

示例:2#

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


相關用法


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