johnrao07
johnrao07

Reputation: 6908

How to remove an item from a MutableSet given a certain condition?

var chart_values: MutableSet<MutableMap.MutableEntry<String, Any>>? = mutableSetOf()

Printing chart_values:

[ground={}, 
ground_level={0=115, 1=4, 2=0, 3=37, 4=63, 5=44, 6=40, 7=9}, 
ground_over={0=3, 1=3, 2=3, 3=3, 4=3, 5=3, 6=3}
date_of_birth=1988-07-18T00:00Z]

I would like to remove ground={} from the chart_values

Upvotes: 0

Views: 1370

Answers (3)

Willi Mentzel
Willi Mentzel

Reputation: 29844

Given that chartValues is of type MutableSet<MutableMap.MutableEntry<String, Any>>? you can do the following to remove any entry with an empty map as a value:

chartValues?.removeAll { (_, value) ->
    (value as? Map<*,  *>)?.isEmpty() == true
}

as? is called safe cast operator and will return the casted object or null if the cast did not succeed.

Note:

  • You might be better off using a MutableMap<String, Any>
  • use val instead of var, since you want to mutate the collection an not the reference to it

Upvotes: 1

johnrao07
johnrao07

Reputation: 6908

fun removeMapEntryIfEmpty() {
        val iterator: MutableIterator<MutableMap.MutableEntry<String, Any>> =
            player.chart_values?.iterator()!!
        iterator.forEach {
            // it: MutableMap.MutableEntry<String, Any>

            if (it.value.toString() == "{}") {
                iterator.remove()

            }
        }
    }

Upvotes: 0

Neo
Neo

Reputation: 2039

BTW:

  • Your set can be actually a map Map<String, Any>
  • chart_values doesnt comply with kotlins naming convetions. Use camel case

Since the value is of type Any - which should be changes to more specific type if possible - we have to check for instance first

val chart_values: MutableSet<MutableMap.MutableEntry<String, Any>>? = mutableSetOf()
val withoutEmptyValues = chart_values.filter { (_, value) -> value is Collection<*> && value.isNotEmpty() } 

EDIT

If some elements are no collections:

val withoutEmptyValues = chart_values.filter { (_, value) -> if(value is Collection<*>) value.isNotEmpty() else true } 

Test

I can't create instances of MutableMap.MutableEntry, so I created a mao which does it for me internally:

    val map: MutableMap<String, Any> = mutableMapOf(
            "ground" to listOf<Int>(1, 2, 3),
            "empty" to emptyList<Double>(),
            "date" to "1988-07-18T00:00Z"
    )

    val withoutEmptyValues = map
            .filter { (_, value) -> if (value is Collection<*>) value.isNotEmpty() else true }

    assertThat(withoutEmptyValues).isNotEmpty.isEqualTo(
            mutableMapOf<String, Any>(
                    "ground" to listOf<Int>(1, 2, 3),
                    "date" to "1988-07-18T00:00Z"
            )
    )

Upvotes: 0

Related Questions