Home > Enterprise >  How to select the last element of each type with in a list and move it at the end of the list in a s
How to select the last element of each type with in a list and move it at the end of the list in a s

Time:11-08

Looking for a functional more concise and optimal way to do achieve the following output.

Input = List of players of different types. Output = Take the last element of each type and append it to the end of the list.

    data class Player(val id: Int, val type: Int)

    val players = listOf<Player>(
        Player(1, 1),
        Player(2, 1),
        Player(3, 2),
        Player(4, 2),
        Player(5, 2),
        Player(6, 2),
        Player(7, 2),
        Player(8, 3),
        Player(9, 3),
        Player(10, 3),
        Player(11, 3),
        Player(12, 3),
        Player(13, 4),
        Player(14, 4),
        Player(15, 4)
    )
    val subs = mutableListOf<Player>()
    subs.add(players.last { it.type == 1 })
    subs.add(players.last { it.type == 2 })
    subs.add(players.last { it.type == 3 })
    subs.add(players.last { it.type == 4 })

    val mainTeamPlayers = players.minus(subs) 
    val finalTeam = mainTeamPlayers   subs
    
    println(finalTeam)
    
}```

CodePudding user response:

Not sure if it's much better but I believe you could create the subs list in a more compact way like this:

val subs = players.associateBy { it.type }.map { it.value }.sortedBy { it.type }

If the players list is already guaranteed to be sorted by type, like you have in the example you don't need to add the last sortedBy

As noted by @Sweeper you could also get the finalTeam in a single line like this:

val finalTeam = players.associateBy { it.type }.map { it.value }.sortedBy { it.type }.let { (players - it)   it }
  • Related