Updated May 26, 2023
Introduction to Scala Find
The find function is used to find elements inside the collection. This find function can be applied to any type of collection data structure. Also, this function is applicable for both immutable and mutable objects in scala i.e. the objects which cannot change it and the objects which are changing themselves frequently, respectively. Find function in scala falls under the AbstractIterator as a concrete method which means methods contain a body.
Syntax and Parameters
The find method takes the first value from the collection, which satisfies the given passed condition as a predicate. It will start iterating the whole collection if the condition does not match. Also, it will run non-stop for infinite collection. Below see the syntax defined by Scala;
find(p: (A) ⇒ Boolean): Option[A]
In the above syntax inside find, I will take one condition which we want to test, also, its return type is Option which means it will return none if the value does not exist in the collection, else it will return the result value from the collection.
find(obj => {obj % 5 == 0}): Option[A]
In the above syntax, we are passing one condition it will return a value which will be divided by 5.
How Find Function Work in Scala?
The find function is used to iterator over the collection elements, and it takes one predicate to match the value. Its return type is Option which means the optional same way it works in Java. Now talk about its class and superclasses in Scala where it is defined and implemented. This method is a member of AbstartIterator which turns extends the iterator class in scala.
Extended class available:
- AbstractTraversable[A]
- Iterable[A]
Some of the supertypes classes available:
- Iterable[A]
- IterableLike[A, Iterable[A]]
- Equals
- GenIterable[A]
- GenIterableLike[A, Iterable[A]]
- AbstractTraversable[A], Traversable[A]
- GenTraversable[A]
- GenericTraversableTemplate[A, Iterable]
- TraversableLike[A, Iterable[A]]
- GenTraversableLike[A, Iterable[A]]
- Parallelizable[A, ParIterable[A]]
- TraversableOnce[A]
- GenTraversableOnce[A]
- FilterMonadic[A, Iterable[A]]
- HasNewBuilder[A, Iterable[A] @scala.annotation.unchecked.uncheckedVariance]
- AnyRef
- Any
Some of the know subclasses available are as follows:
- ValueSet
- AbstractMap
- AbstractSeq
- AbstractSet
- WithDefault
- DefaultKeySet
- DefaultValuesIterable
- FilteredKeys
- MappedValues
- DefaultKeySortedSet
- ::
- AbstractMap
- BitSet
- BitSet1
- BitSet2
- BitSetN
- HashMap
- HashMap1
- HashTrieMap
- HashSet
- HashTrieSet
- Impl
- IntMap
- List
- ListMap
- Node
- ListSet
- Node
- LongMap
- Map1
- Map2
- Map3
- Map4
- WithDefault
- ImmutableDefaultKeySet
- Nil
- NumericRange
- Exclusive
- Inclusive
- Queue
- Range
- Inclusive
- Set1
- Set2
- Set3
- Set4
- DefaultKeySortedSet
- Stream
- Cons
- Empty
- Vector
- WrappedString
- AbstractBuffer
- AbstractIterable
- AbstractMap
- AbstractSeq
- AbstractSet
- AbstractSortedMap
- AbstractSortedSet
- AnyRefMap
- ArrayBuffer
- ArraySeq
- ArrayStack
- BitSet
- HashMap
- HashSet
- History
- LinkedHashMap
- DefaultKeySet
- FilteredKeys
- MappedValues
- LinkedHashSet
- ListBuffer
- ListMap
- LongMap
- WithDefault
- MutableList
- OpenHashMap
- PriorityQueue
- Queue
- RevertibleHistory
- StringBuilder
- TreeMap
- TreeSet
- UnrolledBuffer
- WrappedArray
- ofBoolean
- ofByte
- ofChar
- ofDouble
- ofFloat
- ofInt
- ofLong
- ofRef
- ofShort
- ofUnit
- SystemProperties
- PagedSeq
- Stack
- DoubleLinkedList
- ImmutableMapAdaptor
- ImmutableSetAdaptor
- LinkedList
- PriorityQueueProxy
- QueueProxy
- Stack
- StackProxy
- SynchronizedPriorityQueue
- SynchronizedQueue
- SynchronizedStack
- Script
Now we can have looked at one practice example for beginners where we will see its working;
object Main extends App{
// Your code here!
// first creating iterator
val itr1 = Iterator(2, 10, 4, 55, 15, 120)
// now find function
valfindResult= itr1.find(obj => {obj % 5 == 0})
// now the output printing;
println(findResult)
}
In this example, first, we have to create one Iterator object which contains some values. After that, we apply to find function on the iterator. For that, we have to specify our newly created iterator variable followed by the find function. Here you can see that inside the find function, we have written one condition that the object should be divisible by 5, and the remainder must be equal to ‘0’. As you can see in the above Iterator values, we have so many values that are divisible by ‘5’, but it will print out the first value from the collection.
Keep in mind: We can use any type of iterable object while working with the scala find function, for example, Iterator, List, set, etc.
Examples of Scala Find
In this example, we are providing one Integer Iterator and applying conditions on it using find().
Code:
object Main extends App{
// Your code here!
// first creating iterator
val itr1 = Iterator(2, 10, 4, 55, 15, 120)
val itr2 = Iterator(34, 67, 35, 55, 12, 100)
// now find function
val findResult1= itr1.find(obj => {obj % 5 == 0})
val findResult2= itr2.find(obj => {obj % 2 == 0})
// Displays output
println("value inside itr1 is :::")
println(findResult1)
println("*********************************************")
println("value inside itr2 is :::")
println(findResult2)
}
Output:
Example #2
In this example, we are passing one condition which does not satisfy and print NONE.
Code:
object Main extends App{
// Your code here!
// first creating iterator
val itr1 = Iterator(22, 67, 49, 10, 200,500)
// now find function
val findResult1= itr1.find(obj => {obj % 3 == 0})
// Displays output
println("value inside itr1 is :::")
println(findResult1)
println("*********************************************")
}
Output:
Example #3
In this example, we are dealing with string values inside an iterator with find().
Code:
object Main extends App{
// Your code here!
// first creating iterator
val itr1 = Iterator("hello","bye", "hii", "world", "scala", "language")
// now find function
val findResult1= itr1.find(obj => {
println(obj)
obj.equals("world")
})
// Displays output
println("value inside itr1 is :::")
println(findResult1)
println("*********************************************")
}
Output:
Example #4
In this example, we are using a list to create an iterable object.
Code:
object Main extends App{
// Your code here!
// first creating iterator
val itr1 = List("hello","bye", "hii", "world", "scala", "language")
// now find function
val findResult1= itr1.find(obj => {
println(obj)
obj.equals("abcxyz")
})
// Displays output
println("value inside itr1 is :::")
println(findResult1)
println("*********************************************")
}
Output:
Example #5
In this example, we are using a set to create an iterable object and apply the find function on it.
Code:
object Main extends App{
// Your code here!
// first creating iterator
val itr1 = Set("amit","amita", "ajay", "akash", "atul", "avinash")
// now find function
val findResult1= itr1.find(obj => {
println(obj)
obj.equals("avinash")
})
// Displays output
println("value inside itr1 is :::")
println(findResult1)
println("*********************************************")
}
Output:
Conclusion
Scala find function is used to find the value among the elements present in the collection. We can create an iterator object for that. It can work with both the type mutable and immutable collections. One thing we have to keep in mind is we have to pass on the condition inside the find function. Otherwise, it will not work and will generate an error.
Recommended Articles
We hope that this EDUCBA information on “Scala Finds” was beneficial to you. You can view EDUCBA’s recommended articles for more information.