In this article , lets discuss about Kotlin Collections operation - Plus-Minus and grouping functions
Plus and Minus
In Kotlin , + and - operators are used in collection
The first operand is a collection where as second operand can either be an element or another collection
returns a read only collection
Plus ( + )
- return a collection containing elements from both first and second operand
Minus ( - )
returns a collection containing elements from original collection except the elements of second operand
If the second operand is
an element , minus remove its first occurrence
a collection , all occurrence of its elements are removed
val numberList = listOf(1, 3, 5, 7, 9)
val numberOperand = listOf(3, 5)
val plusResultList = numberList.plus(numberOperand)
println(plusResultList)
// output : [1, 3, 5, 7, 9, 3, 5]
val minusResultList = numberList.minus(numberOperand)
println(minusResultList)
//output : [1, 7, 9]
val number = 7
val resultList = numberList.minus(number)
println(resultList)
//output : [1, 3, 5, 9]
Grouping
groupBy()
takes a lambda function and returns a map
In the Result
key - lambda result
value- list of elements on which the lambda result is obtained
val numbers = listOf(22, 56, 44, 67, 88, 45, 77) // groupBy val groupByResult = numbers.groupBy { it % 11 == 0 } println(groupByResult) //output : {true=[22, 44, 88, 77], false=[56, 67, 45]}
groupBy()
- 2 Lambda argument
Second lambda argument is a value transformation function
In Result
key - produced by
keySelector
functionvalue - result of
valueTransform
function
val numbers = listOf(22, 56, 44, 67, 88, 45, 77)
val result = numbers.groupBy(
keySelector = { it % 2 == 0 },
valueTransform = {
if (it % 2 == 0) {
"$it is an Even number"
} else {
"$it is not an Even number"
}
})
println(result)
//output : {
// true=[22 is an Even number,
// 56 is an Even number,
// 44 is an Even number,
// 88 is an Even number],
// false=[67 is not an Even number,
// 45 is not an Even number,
// 77 is not an Even number]}
groupingBy()
helps to group elements and apply an operation to all groups at one time
returns an instance of Grouping type
applies the operation in lazy manner : the groups are actually built right before the operation execution
supports the following execution
1.
eachCount()
- counts the element in each group2.
fold()
&reduce()
- perform fold and reduce operations on each group as separate collection and return results3.
aggregate()
- applies a given operation subsequently to all elements in each group and return results
val oddNumbers = listOf(1, 7, 5, 7, 9)
val groupingByResult = oddNumbers.groupingBy {
it * 2
}.eachCount()
println(groupingByResult)
// output : {2=1, 14=2, 10=1, 18=1}
Please leave your comments to improve.
Happy and Enjoy coding