Scala | Функция reduce ()
Метод reduce () - это функция высшего порядка, которая берет все элементы в коллекции (массив, список и т. Д.) И объединяет их с помощью бинарной операции для создания единого значения. Необходимо убедиться, что операции коммутативны и ассоциативны. Анонимные функции передаются в качестве параметра функции уменьшения.
Синтаксис :
val l = Список (2, 5, 3, 6, 4, 7) // возвращает наибольшее число из коллекции l.reduce ((x, y) => x max y)
The order in which numbers are selected for operation by the reduce method is random. This is the reason why non-commutative and non-associative operations are not preferred.
Example :
scala
// Scala program to // print maximum value // using reduce() // Creating object object GfG { // Main method def main(args : Array[String]) { // source collection val collection = List( 1 , 3 , 2 , 5 , 4 , 7 , 6 ) // finding the maximum valued element val res = collection.reduce((x, y) => x max y) println(res) } } |
Выход :
7
In the above program, the reduce method selects random pairs and finds out the maximum value in a particular pair. These values are again compared with each other until a single maximum valued element is obtained. We generally make use of the reduce() method along with the map() method while working with Resilient Distributed Datasets in Spark. The map() method helps us to transform a collection to another collection while the reduce() method allows us to perform some action.
Finding average using map() and reduce():
Example :
scala
// Scala program to // print average // using map() and reduce() //Creating object object GfG { // Main method def main(args : Array[String]) { // source collection val collection = List( 1 , 5 , 7 , 8 ) // converting every element to a pair of the form (x,1) // 1 is initial frequency of all elements val new _ collection = collection.map(x => (x, 1 )) /* List((1, 1), (5, 1), (7, 1), (8, 1)) */ // adding elements at corresponding positions val res = new _ collection.reduce( (a,b) => ( a. _ 1 + b. _ 1 , a. _ 2 + b. _ 2 ) ) /* (21, 4) */ println(res) println( "Average=" + res. _ 1 /res. _ 2 .toFloat) } } |
Выход :
(21, 4) Среднее значение = 5,25
В приведенной выше программе все элементы коллекции преобразованы в кортежи с двумя элементами. Первым элементом кортежа является само число, а вторым элементом - счетчик. Изначально все счетчики установлены на 1. Сам вывод представляет собой кортеж с двумя элементами: первое значение - это сумма, а второе - количество элементов.
Примечание . Тип вывода, выдаваемый методом reduce (), совпадает с типом элементов коллекции.