课程: Java Algorithms

今天就学习课程吧!

今天就开通帐号,24,700 门业界名师课程任您挑!

Linear search arrays with Java streams

Linear search arrays with Java streams - Java教程

课程: Java Algorithms

Linear search arrays with Java streams

- [Instructor] While we can search for data in arrays, using for loops, we can simplify our implementation quite a bit using Java streams. We can turn the array into a stream and filter out data based on a condition to find the data we're searching for. To turn an array into a stream, we can use the stream function from the arrays class. Then we'll pass in our array, we'll also import the array class at the top. As we stream through each element or go through each element, we'll want to filter based on a condition. In this case, that's whether a given element equals the element we're searching for. Then we can see if at least one item meets the condition using find first. Now this find first call will return an optional, specifically an OptionalInt. This is also something we'll need to import. An optional acts as a container object to help prevent null exceptions. In our case, if the array contains the number, then the optional will contain the item. If the array does not contain the…

内容