Showing posts with label MutableList. Show all posts
Showing posts with label MutableList. Show all posts

Count Occurrences in List item and String in KOTLIN

 



Here is some way to find out how to count list item from the list, only first char in list and many more;

1. Count first character with start particular char on list 

fun countOccurrencesOnlyFirstCharUsingCount() {
val list = listOf("one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten")
val char = 't'
val count = list.count { it.startsWith(char) }
println("$char => $count")
}

output:

/*
t => 3
*/

2. Count occurrence first all characters on list

fun countOccurrencesFirstCharUsingGroupingBy() {
val list = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten")
val frequenciesByFirstChar = list.groupingBy { it.first() }.eachCount()
println(frequenciesByFirstChar) // {o=1, t=3, f=2, s=2, e=1, n=1}
}

output:

/*
{o=1, t=3, f=2, s=2, e=1, n=1}
*/


3. Count occurrence of word in list by using groupingBy and eachCount

fun countOccurrencesUsingGroupingBy() {
val list = listOf("usa", "china","japan","usa", "canada","usa","canada", "japan", "india","japan")
println(list.groupingBy { it }.eachCount())

}

output:

/*
{usa=3, china=1, japan=3, canada=2, india=1}
*/

4. Count occurrence of word in list by using  MutableMap and for loop

fun countOccurrencesUsingMutableMap() {
val list = listOf("usa", "china","japan","usa", "canada","usa","canada", "japan", "india","japan")
val countMap : MutableMap<String, Int> = HashMap()
for (item in list){
var count = countMap[item]
if (count == null) count = 0
countMap[item] = count + 1
}
println(countMap)
}

output:

/*
{usa=3, china=1, canada=2, japan=3, india=1}
*/

5. Count occurrence of word in list by using distinctCollections and, frequency

fun countOccurrencesUsingCollection() {
val list:List<String> = listOf("usa", "china","japan","usa", "canada","usa","canada", "japan", "india","japan")
for(i in list.distinct()){
println( "$i => ${Collections.frequency( list, i)}")
}
}

output:

/*
usa => 3
china => 1
japan => 3
canada => 2
india => 1
*/

6. Count occurrence of word in list without (expect) banned word or list   (.filterNotgroupingBy ,  eachCount)

with help fo HashSet.

fun countOccurrencesUsingGroupingByBannedItem() {
val list = listOf("usa", "china","japan","usa", "canada","usa","canada", "japan", "india","japan")

val banned = setOf("china","india")
var bannedSet = banned.toHashSet()

val wordCount = list.filterNot { it in bannedSet }.groupingBy { it } .eachCount()
println(wordCount)
}

output:

/*
{usa=3, japan=3, canada=2}
*/


HAPPY CODING :) 

Sorting Array, List, Custom Object and Dates in Kotlin

 Here is some sorting example in KOTLIN.

Sorting Array using ArrayOf

----------

fun sortedArrayOf() {
val array1 = arrayOf(44,6,1,9,23,11,5,19,3)
array1.sort()
println("Sorted array : ${array1.contentToString()}")
}
//output
/*
Sorted array : [1, 3, 5, 6, 9, 11, 19, 23, 44]
*/

IntArray Sorting

----------

fun sortingByIntArray() {
val intArray = intArrayOf(4, 3, 2, 1)
intArray.sort()
println(intArray.joinToString())
// output : 1, 2, 3, 4
}

 Sorting Alphabetically String Array

---------

fun sortingByAlphabetically() {
val stringArray = mutableListOf("ccc", "aab","aaa", "zzz", "bbb")
val tempSortedList = stringArray.sortedWith(compareBy { it }) //it.first() is for first letter only
println("Sorted by ascending: $tempSortedList")
//output: Sorted by ascending: [aaa, aab, bbb, ccc, zzz]
}


Get the first element of String Array

---------

fun getFirstDataOfList() {
val stringArray = mutableListOf("ccc", "aab","aaa", "zzz", "bbb")
val firstElement = stringArray.first()
println("First Element: $firstElement")
//output : First Element: ccc
}

Sorting Date Ascending

---------

fun sortingByDates() {
val dates = mutableListOf(
Date(2020, 3, 8),
Date(2022, 8, 16),
Date(2020, 1, 30),
Date(1999, 1, 5)
)
//useing sortBy
dates.sortBy { it.toString() }
dates.forEach { println(it) }
println(".........")
//using sortWith
dates.sortWith(compareBy<Date> { it.year }.thenBy { it.month }.thenBy { it.day })
dates.forEach { println(it) }
//for descending: dates.reverse()
println(".........")
//using sortedWith
val sortedDates = dates.sortedWith(compareBy<Date> { it.year }.thenBy { it.month }.thenBy { it.day })
sortedDates.forEach { println(it) }
//use for descending .reversed()
}

data class Date(val year: Int, val month: Int, val day: Int)

//output
/*
Date(year=1999, month=1, day=5)
Date(year=2020, month=1, day=30)
Date(year=2020, month=3, day=8)
Date(year=2022, month=8, day=16)
.........
Date(year=1999, month=1, day=5)
Date(year=2020, month=1, day=30)
Date(year=2020, month=3, day=8)
Date(year=2022, month=8, day=16)
.........
Date(year=1999, month=1, day=5)
Date(year=2020, month=1, day=30)
Date(year=2020, month=3, day=8)
Date(year=2022, month=8, day=16)
*/


Sorting Ascending array by adding manually 

---------

fun sortByAddingManually() {
val stringList: MutableList<String> = ArrayList()
stringList.add("ccc")
stringList.add("aab")
stringList.add("aaa")
stringList.add("zzz")
stringList.add("bbb")
stringList.sortBy { it }
stringList.forEach { println(it) }
}
//output
//aaa
//aab
//bbb
//ccc
//zzz


Sorting by custom object

---------------------------

fun sortedCustomObject() {
val persons: MutableList<People> = ArrayList()
persons.add(People("ABC", 61))
persons.add(People("XZY", 30))
persons.add(People("ABB",61))
persons.add(People("XYZ",30))
persons.add(People("ABZ",61))

println(".....Sorted Overall Object.....")
persons.sortBy { it.toString() }
persons.forEach { println(it) }
println(".....Sorted First Name and then Age.....")
val sortedListName = persons.sortedWith(compareBy({ it.name }, { it.age }))
sortedListName.forEach { println(it) }
println(".....Sorted First Age and then Name.....")
val sortedListAge = persons.sortedWith(compareBy({ it.age }, { it.name }))
sortedListAge.forEach { println(it) }
println(".....Sorted First Age and then Name...thenBy....")
persons.sortedWith(compareBy<People> { it.name }.thenBy { it.age })
persons.forEach { println(it) }
println(".....using lambda...")
persons.sortBy { person -> person.age}
persons.forEach { println(it) }

}
data class People(val name:String, val age: Int)

//output
/*
.....Sorted Overall Object.....
People(name=ABB, age=61)
People(name=ABC, age=61)
People(name=ABZ, age=60)
People(name=XYZ, age=30)
People(name=XZY, age=30)
.....Sorted First Name and then Age.....
People(name=ABB, age=61)
People(name=ABC, age=61)
People(name=ABZ, age=60)
People(name=XYZ, age=30)
People(name=XZY, age=30)
.....Sorted First Age and then Name.....
People(name=XYZ, age=30)
People(name=XZY, age=30)
People(name=ABZ, age=60)
People(name=ABB, age=61)
People(name=ABC, age=61)
*/

More details:

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sorted.html

I will try to adding more frequently, please keep visiting this blog.