Сумма чисел в массиве kotlin

Array

Represents an array (specifically, a Java array when targeting the JVM platform). Array instances can be created using the arrayOf, arrayOfNulls and emptyArray standard library functions. See Kotlin language documentation for more information on arrays.

For Native

Represents an array. Array instances can be created using the constructor, arrayOf, arrayOfNulls and emptyArray standard library functions. See Kotlin language documentation for more information on arrays.

Constructors

Creates a new array with the specified size, where each element is calculated by calling the specified init function.

Properties

size

Returns the number of elements in the array.

Functions

get

Returns the array element at the specified index. This method can be called using the index operator.

iterator

Creates an Iterator for iterating over the elements of the array.

set

Sets the array element at the specified index to the specified value. This method can be called using the index operator.

Extension Properties

indices

Returns the range of valid indices for the array.

Читайте также:  Vue html self closing

lastIndex

Returns the last valid index for the array.

Extension Functions

all

Returns true if all elements match the given predicate.

any

Returns true if array has at least one element.

Returns true if at least one element matches the given predicate.

asIterable

Creates an Iterable instance that wraps the original array returning its elements when being iterated.

asSequence

Creates a Sequence instance that wraps the original array returning its elements when being iterated.

associate

Returns a Map containing key-value pairs provided by transform function applied to elements of the given array.

associateBy

Returns a Map containing the elements from the given array indexed by the key returned from keySelector function applied to each element.

Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given array.

associateByTo

Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function applied to each element of the given array and value is the element itself.

Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function and and value is provided by the valueTransform function applied to elements of the given array.

fun < T , K , V , M : MutableMap < in K , in V >> Array < out T >. associateByTo (
destination : M ,
keySelector : ( T ) -> K ,
valueTransform : ( T ) -> V
) : M

associateTo

Populates and returns the destination mutable map with key-value pairs provided by transform function applied to each element of the given array.

associateWith

Returns a Map where keys are elements from the given array and values are produced by the valueSelector function applied to each element.

associateWithTo

Populates and returns the destination mutable map with key-value pairs for each element of the given array, where key is the element itself and value is provided by the valueSelector function applied to that key.

average

Returns an average value of elements in the array.

binarySearch

Searches the array or the range of the array for the provided element using the binary search algorithm. The array is expected to be sorted according to the specified comparator, otherwise the result is undefined.

fun < T >Array < out T >. binarySearch (
element : T ,
comparator : Comparator < in T >,
fromIndex : Int = 0 ,
toIndex : Int = size
) : Int

Searches the array or the range of the array for the provided element using the binary search algorithm. The array is expected to be sorted, otherwise the result is undefined.

component1

Returns 1st element from the array.

component2

Returns 2nd element from the array.

component3

Returns 3rd element from the array.

component4

Returns 4th element from the array.

component5

Returns 5th element from the array.

contains

Returns true if element is found in the array.

contentEquals

Returns true if the two specified arrays are structurally equal to one another, i.e. contain the same number of the same elements in the same order.

contentHashCode

Returns a hash code based on the contents of this array as if it is List.

contentToString

Returns a string representation of the contents of the specified array as if it is List.

count

Returns the number of elements in this array.

Returns the number of elements matching the given predicate.

distinct

Returns a list containing only distinct elements from the given array.

distinctBy

Returns a list containing only elements from the given array having distinct keys returned by the given selector function.

drop

Returns a list containing all elements except first n elements.

dropLast

Returns a list containing all elements except last n elements.

dropLastWhile

Returns a list containing all elements except last elements that satisfy the given predicate.

dropWhile

Returns a list containing all elements except first elements that satisfy the given predicate.

elementAtOrElse

Returns an element at the given index or the result of calling the defaultValue function if the index is out of bounds of this array.

elementAtOrNull

Returns an element at the given index or null if the index is out of bounds of this array.

filter

Returns a list containing only elements matching the given predicate.

filterIndexed

Returns a list containing only elements matching the given predicate.

filterIndexedTo

Appends all elements matching the given predicate to the given destination.

fun < T , C : MutableCollection < in T >> Array < out T >. filterIndexedTo (
destination : C ,
predicate : ( index : Int , T ) -> Boolean
) : C

filterIsInstance

Returns a list containing all elements that are instances of specified type parameter R.

Returns a list containing all elements that are instances of specified class.

filterIsInstanceTo

Appends all elements that are instances of specified type parameter R to the given destination.

Appends all elements that are instances of specified class to the given destination.

filterNot

Returns a list containing all elements not matching the given predicate.

filterNotNull

Returns a list containing all elements that are not null .

filterNotNullTo

Appends all elements that are not null to the given destination.

filterNotTo

Appends all elements not matching the given predicate to the given destination.

filterTo

Appends all elements matching the given predicate to the given destination.

find

Returns the first element matching the given predicate, or null if no such element was found.

findLast

Returns the last element matching the given predicate, or null if no such element was found.

first

Returns the first element.

Returns the first element matching the given predicate.

firstNotNullOf

Returns the first non-null value produced by transform function being applied to elements of this array in iteration order, or throws NoSuchElementException if no non-null value was produced.

firstNotNullOfOrNull

Returns the first non-null value produced by transform function being applied to elements of this array in iteration order, or null if no non-null value was produced.

firstOrNull

Returns the first element, or null if the array is empty.

Returns the first element matching the given predicate, or null if element was not found.

flatMap

Returns a single list of all elements yielded from results of transform function being invoked on each element of original array.

flatMapIndexed

Returns a single list of all elements yielded from results of transform function being invoked on each element and its index in the original array.

flatMapIndexedTo

Appends all elements yielded from results of transform function being invoked on each element and its index in the original array, to the given destination.

fun < T , R , C : MutableCollection < in R >> any_array . flatMapIndexedTo (
destination : C ,
transform : ( index : Int , T ) -> Iterable < R >
) : C

flatMapTo

Appends all elements yielded from results of transform function being invoked on each element of original array, to the given destination.

fun < T , R , C : MutableCollection < in R >> any_array . flatMapTo (
destination : C ,
transform : ( T ) -> Iterable < R >
) : C

flatten

Returns a single list of all elements from all arrays in the given array.

fold

Accumulates value starting with initial value and applying operation from left to right to current accumulator value and each element.

foldIndexed

Accumulates value starting with initial value and applying operation from left to right to current accumulator value and each element with its index in the original array.

foldRight

Accumulates value starting with initial value and applying operation from right to left to each element and current accumulator value.

foldRightIndexed

Accumulates value starting with initial value and applying operation from right to left to each element with its index in the original array and current accumulator value.

forEach

Performs the given action on each element.

forEachIndexed

Performs the given action on each element, providing sequential index with the element.

getOrElse

Returns an element at the given index or the result of calling the defaultValue function if the index is out of bounds of this array.

getOrNull

Returns an element at the given index or null if the index is out of bounds of this array.

groupBy

Groups elements of the original array by the key returned by the given keySelector function applied to each element and returns a map where each group key is associated with a list of corresponding elements.

Groups values returned by the valueTransform function applied to each element of the original array by the key returned by the given keySelector function applied to the element and returns a map where each group key is associated with a list of corresponding values.

groupByTo

Groups elements of the original array by the key returned by the given keySelector function applied to each element and puts to the destination map each group key associated with a list of corresponding elements.

Groups values returned by the valueTransform function applied to each element of the original array by the key returned by the given keySelector function applied to the element and puts to the destination map each group key associated with a list of corresponding values.

fun < T , K , V , M : MutableMap < in K , MutableList < V >> > Array < out T >. groupByTo (
destination : M ,
keySelector : ( T ) -> K ,
valueTransform : ( T ) -> V
) : M

Источник

Вычислить сумму всех элементов в списке целых чисел в Kotlin

В этой статье рассматриваются различные способы вычисления суммы всех элементов списка целых чисел в Kotlin.

1. Использование sum() функция

Простое решение для вычисления суммы всех элементов в списке вызывает метод sum() функция. Он доступен для списка всех числовых типов данных. т.е., Int , Long , Float , Double , Byte , Short .

Чтобы получить сумму определенного поля внутри списка объектов, вы можете использовать sumBy() функция. Если поле двойное, используйте sumByDouble() функция:

Обратите внимание, что начиная с Kotlin 1.5, sumBy() функция устарела. Вы должны использовать sumOf() функция вместо этого.

Кроме того, вы можете преобразовать каждый объект элемента в соответствующее поле, используя map() функция. Наконец, верните сумму, используя sum() функция. Это особенно полезно для преобразования и суммирования других типов данных.

2. Сокращение работы

Другой жизнеспособной альтернативой является выполнение операции сокращения списка, чтобы получить сумму всех элементов в нем. Типичная реализация этого подхода будет выглядеть так:

3. Использование summaryStatistics() функция

Если вам нужны другие статистические данные об элементах списка, таких как минимум, максимум, среднее и т. д., рассмотрите возможность использования summaryStatistics() Функция примитивного потока.

4. Наивное решение

Наконец, вы можете вычислить сумму всех элементов в списке, используя цикл for, как показано ниже:

Это все о вычислении суммы всех элементов в списке целых чисел в Kotlin.

Средний рейтинг 5 /5. Подсчет голосов: 2

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

Оцените статью