Scala check if element is present in a list

后端 未结 6 1821
刺人心
刺人心 2021-01-30 19:45

I need to check if a string is present in a list, and call a function which accepts a boolean accordingly.

Is it possible to achieve this with a one liner?

The c

相关标签:
6条回答
  • 2021-01-30 19:52

    In your case I would consider using Set and not List, to ensure you have unique values only. unless you need sometimes to include duplicates.

    In this case, you don't need to add any wrapper functions around lists.

    0 讨论(0)
  • 2021-01-30 19:55

    You can also implement a contains method with foldLeft, it's pretty awesome. I just love foldLeft algorithms.

    For example:

    object ContainsWithFoldLeft extends App {
    
      val list = (0 to 10).toList
      println(contains(list, 10)) //true
      println(contains(list, 11)) //false
    
      def contains[A](list: List[A], item: A): Boolean = {
        list.foldLeft(false)((r, c) => c.equals(item) || r)
      }
    }
    
    0 讨论(0)
  • 2021-01-30 19:59

    Just use contains

    myFunction(strings.contains(myString))
    
    0 讨论(0)
  • 2021-01-30 20:03

    this should work also with different predicate

    myFunction(strings.find( _ == mystring ).isDefined)
    
    0 讨论(0)
  • 2021-01-30 20:07

    And if you didn't want to use strict equality, you could use exists:

    
    myFunction(strings.exists { x => customPredicate(x) })
    
    0 讨论(0)
  • 2021-01-30 20:07

    Even easier!

    strings contains myString
    
    0 讨论(0)
提交回复
热议问题