Kotlin GroupBy

Kotlin Tutorial this post, how to create group by data. That is used to section, Sticky Header in programming language (for example android, ios, kotlin, flutter).

  • comp1, comp2 set your data order by asc or desc.
  • groupby
  • groupby data store list
  • Gson library use show data json format.

Kotlin GroupBy

import com.google.gson.Gson

fun main(args : Array<String>)  {
    val students = listOf(Student("Sachin", 54), Student("Sachin", 54), Student("Jasprit Bumrah", 34),
        Student("Cristiano Ronaldo", 11), Student("Jasprit Bumrah", 90))  as MutableList<Student>

    students.sortWith(Comparator { comp1, comp2 ->
        comp1.name.compareTo(comp2.name)
    })
    val groupByName = students.groupBy { it -> it.name }

    var listQuiz = ArrayList<StudentGroup>()
    for (groupBy in groupByName) {
        listQuiz.add(StudentGroup(groupBy.key, groupBy.value))
    }

    println(Gson().toJson(listQuiz))
}

class Student(val name: String, val marks : Int)

class StudentGroup(var name: String, var studentList: List<Student>)

/*
[
  {
    "name": "Cristiano Ronaldo",
    "studentList": [
      {
        "name": "Cristiano Ronaldo",
        "marks": 11
      }
    ]
  },
  {
    "name": "Jasprit Bumrah",
    "studentList": [
      {
        "name": "Jasprit Bumrah",
        "marks": 34
      },
      {
        "name": "Jasprit Bumrah",
        "marks": 90
      }
    ]
  },
  {
    "name": "Sachin",
    "studentList": [
      {
        "name": "Sachin",
        "marks": 54
      },
      {
        "name": "Sachin",
        "marks": 54
      }
    ]
  }
]
*/

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in