Scala TreeSet sum()方法及示例

Scala TreeSet sum()方法及示例

sum() 方法是用来返回TreeSet中所有元素的总和。

方法定义: def sum:A

返回类型。它返回TreeSet中所有元素的总和。

例子 #1:

// Scala program of sum() 
// method 
  
// Import TreeSet
import scala.collection.mutable._
  
// Creating object 
object GfG 
{ 
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating TreeSet
        val t1 = TreeSet(3, 1, 5, 2, 4)  
            
        // Print the TreeSet 
        println(t1) 
          
        // Applying sum method  
        val result = t1.sum
            
        // Displays output  
        print("Sum of all the elements of the TreeSet: " + result) 
          
    } 
} 
Scala

输出。

TreeSet(1, 2, 3, 4, 5)
Sum of all the elements of the TreeSet: 15
Scala

例子#2。

// Scala program of sum() 
// method 
  
// Import TreeSet
import scala.collection.mutable._
  
// Creating object 
object GfG 
{ 
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating TreeSet
        val t1 = TreeSet(3, 1, 5, 7, 9)  
            
        // Print the TreeSet 
        println(t1) 
          
        // Applying sum method  
        val result = t1.sum
            
        // Displays output  
        print("Sum of all the elements of the TreeSet: " + result) 
          
    } 
} 
Scala

输出。

TreeSet(1, 3, 5, 7, 9)
Sum of all the elements of the TreeSet: 25
Scala

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册