NikhilReddy
NikhilReddy

Reputation: 6954

Filter the values from list between 3000 and 3500

I am trying to filter the records from list between two numbers (3000 and 3500) and I am facing some issues with filtering and below is my syntax.

  val values = 1800
  val test = listOf(1818, 2000, 3200, 3250, 3800, 4500)
  val filterValue = test.filter { values in 3000..3500 }
  println("Test::>$filterValue")

The output should be

Test::> [3200,3250]

Upvotes: 0

Views: 186

Answers (2)

ivan8m8
ivan8m8

Reputation: 447

According to the documentation:

in

  • is used as an infix operator to check that a value belongs to a range, a collection or another entity that defines the 'contains' method

So, the appropriate answer would be:

listOfValues.filter { it in 3000..3500 }

Notice, that the values are returned inclusive.

Upvotes: 1

matej-m
matej-m

Reputation: 147

I think that a solution from @ivan8m8 should work.

Short example on the list of primitive integer values:

val listOfValues = listOf(1000, 1500, 2000, 2500, 3000, 3100, 3250, 3500, 4000, 4500, 5000)

for(value in listOfValues.filter { it in 3000..3500 }) {
    println(value)
}

The output from the program is:

3000
3100
3250
3500

Upvotes: 2

Related Questions