how to customized sorting in an enum class in kotlin

how to customized sorting in an enum class in kotlin

Content Index :

how to customized sorting in an enum class in kotlin
Tag : sorting , By : n3txpert
Date : November 24 2020, 05:47 AM

wish of those help From the look of your code I suspect you have some class (e.g. Order) which has an optional property called ProductItem, which returns a ProductItem enum value. And you then have a list or array of these Order objects, which you want to sort by the position of the associated ProductItem. Is that correct?
If so, here's some code below which shows how the list of orders can be sorted...
enum class ProductItem constructor(
        val color: String,
        val price: String,
        val position: Int
) {
    SHOES("red", "$", 2),
    CAR("blue", "$$$$$", 1),
    BOAT("green", "$$$$$$$$$$$$$", 3)

data class Order(val ProductItem: ProductItem? = null)

val orders = listOf(Order(ProductItem.SHOES), Order(ProductItem.CAR), Order(ProductItem.BOAT))
val sortedOrders = orders.sortedBy { it.ProductItem?.position }

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to get enum value of raw type from an enum class and a string in kotlin

Tag : generics , By : adbanginwar
Date : March 29 2020, 07:55 AM
I wish this help you I have the following code in java: , Here's a pure Kotlin version:
fun getEnumValue(enumClass: Class<*>, value: String): Enum<*> {
    val enumConstants = enumClass.enumConstants as Array<out Enum<*>>
    return enumConstants.first { it.name == value }
private enum class Hack

fun getEnumValue(enumClass: Class<*>, value: String): Enum<*> {
    return helper<Hack>(enumClass, value)

private fun <T : Enum<T>>helper(enumClass: Class<*>, value: String): Enum<*> {
    return java.lang.Enum.valueOf(enumClass as Class<T>, value)
enum class Color {
    Red, Green, Blue


Kotlin! How to create a inner enum class to get some property from outer class?

Tag : kotlin , By : Kocur
Date : March 29 2020, 07:55 AM
hop of those help? Enum constants need to exist without having to be initialized explicitly, whereas the surrounding class OutA needs to be created first. You cannot access non-static values from static contexts. Making the class a singleton, i.e. an object, will make the code compile though:
object OutA {
    var var1 = ""

    enum class A2 {
        init {

Replacing an Interface or Abstract Class with a Single Class and Enum Parameter (Kotlin)

Tag : oop , By : Caleb Ames
Date : March 29 2020, 07:55 AM
wish of those help for the suggestions and encouragement. From Yoni Gibbs' comment, Sealed Classes was the "trick" I was seeking, that is some combination of Enum and Polymorphism. In regards to Generics, it took two Types to encapsulate the underling storage object and how the pixels are represented. Here is the result that combines all the suggestions.
//e.g. T=ByteArray, ShortArray
//e.g. E=Byte,Short
sealed class Frames<T,E>(val nrow:Int,val ncol:Int,val bitDepth:Int,val channelDepth:Int) {
  val size=nrow*ncol //frame size
  abstract val list:MutableList<T>
  fun totalBytes() = list.size*size*bitDepth/8*channelDepth
  abstract fun set(i:Int,data:E)
  abstract fun get(i:Int): E

  fun saveToDisk(filename:String)=saveByteArray(filename,toByteArray())
    abstract fun toByteArray(isSmallEndian:Boolean=false):ByteArray

class Gray8Frame(nrow:Int,ncol:Int) :
    Frames<ByteArray,Byte>(nrow,ncol,8,1) {
  override val list= mutableListOf<ByteArray>()
  override fun set(i: Int,data:Byte) {list[i/size][i%size]=data}
  override fun get(i: Int)=list[i/size][i%size]
  override fun toByteArray(isSmallEndian: Boolean)
        = ByteArray(totalBytes()){get(it)}
class Gray16Frame(nrow:Int,ncol:Int) :
    Frames<ShortArray,Short>(nrow,ncol,16,1) {
  override val list= mutableListOf<ShortArray>()
  override fun set(i: Int,data:Short) {list[i/size][i%size]=data}
  override fun get(i: Int)=list[i/size][i%size]
  override fun toByteArray(isSmallEndian: Boolean)
        = list.flatMap { it.toByteList() }.toByteArray() 
        //implement short-->List<Byte>

class RGBFrame(nrow:Int,ncol:Int) :
    Frames<ByteArray,List<Byte>>(nrow,ncol,8,3) {
  override val list= mutableListOf<ByteArray>()
  override fun set(i: Int,data:List<Byte>) {
  override fun get(i: Int)=listOf(
    list[i/size][3*i%size+2] //Blue
  override fun toByteArray(isSmallEndian: Boolean)
        = list.flatMap { it.asList() }.toByteArray()

fun saveByteArray(filename:String, byteArray: ByteArray) { } //save bytes here

Kotlin sealed class - how to sort by sealed class similar to sorting by enum

Tag : sorting , By : Hibame
Date : March 29 2020, 07:55 AM
around this issue Maybe not completely what you are looking for, but maybe it is...
While the sealed classes don't seem to have something like an ordinal, which you've already noticed, there is sealedSubclasses on the class itself (i.e. GoodCountries::class.sealedSubclasses). Also, it seems as if the order of the sealedSubclasses is the one of the defined classes, i.e. Brazil in this list always comes first, USA second, etc. The order is different if they aren't all nested (i.e. if some are outside, they are listed first).
val entityList = listOf(Germany(), China(), USA(), Brazil(), Germany())
entityList.sortedBy { // or use sortedWith(compareBy {
}.forEach(::println) // or toList...
    .flatMap { klazzInOrder ->
      entityList.asSequence().filter { it::class == klazzInOrder }
println("Listing the sealed classes in the order of their declaration*")

println("Listing the sealed classes ordered by their simple name")
GoodCountries::class.sealedSubclasses.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.simpleName!! })
// same result, but written differently
GoodCountries::class.sealedSubclasses.sortedBy { it.simpleName?.toLowerCase() }
GoodCountries::class.sealedSubclasses.sortedWith(compareBy(nullsLast(String.CASE_INSENSITIVE_ORDER)) { it.simpleName })

Access enum value inside a method of enum class in Kotlin

Tag : development , By : lamberms
Date : March 29 2020, 07:55 AM
wish help you to fix your issue You can use this and this.ordinal which returns the ordinal of this enumeration constant
Also if you do this:
fun myFunc(): Any{
    val array = MyEnum.values()
    return array[this.ordinal]
Related Posts Related QUESTIONS :
  • How to sort a list of structs based on the lastName variable of the struct
  • Kotlin Comparator after converting from Java Comparator
  • Sorting documents in N1QL using array field of the document
  • Sorting and subscribing a Knockout observable array at the same time
  • BootstrapVue table : sort by date and by string?
  • How to reverse sort a map and send it to model in go lang
  • Dynamic chained sorting of a vector by struct fields
  • Elasticsearch ordering by field value which is not in the filter
  • ENUM and Sorting in an arraylist
  • Sorting a list using Composition of comparator
  • Complex Join in SAS
  • Finding the maximum value of an array in log2 time in Verilog?
  • Sort field separator problem in external awk call if its semicolon
  • How to implement sort in hadoop?
  • Julia: Sorting a dict of types
  • Getting specific key from factor object using doc value in Elasticsearch
  • Sort typeahead suggestions with the exact input at top
  • Minizinc array sorting
  • Sorting Map/TreeMap/LinkedHashMap by Value (custom data structures)
  • sorting lists of lists in haskell
  • Sorting in ServiceNow - First by priority and then by updated Timestamp
  • In Haskell, how can you sort a list of infinite lists of strings?
  • How to sort last four files in a google drive folder via google-apps-script?
  • Sort slice of structs by Time date field in go 1.2 without creating a secondary structure
  • Kubernetes: Display Pods by age in ascending order
  • How to sort List in dart based on value returned by a function
  • How to change Ord instance for tuple of type (String, Int) without declaring a new data?
  • Inconsistent Alphanumeric Sorting with ag-grid and String Cells
  • How to sort table if value is itself a table
  • Date conversion in SAS (String to Date)
  • "Sort" =QUERY statement in Google Sheets
  • Finding maximum in itab without using the sort statement?
  • Sorting in Kotlin
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com