Reputation: 26498
I have a collection of items as under
List<String> lstRollNumber = new ArrayList<String>();
lstRollNumber.add("1");
lstRollNumber.add("2");
lstRollNumber.add("3");
lstRollNumber.add("4");
Now I want to search a particular RollNumber
in that collection. Say
String rollNumberToSearch = "3";
I can easily do it by looping through the collection and checking for every items and if there is any match, i can break through the loop and return a true from the function.
But I want to use the Lambda expression for doing this.
In C# we use(among other options),
var flag = lstRollNumber.Exists(x => x == rollNumberToSearch);
How to do the same in Java 1.8 ?
I tried with
String rollNumberToSearch = "3";
Stream<String> filterRecs = lstRollNumbers.stream().filter(rn -> rn.equals(rollNumberToSearch));
But I know it is wrong? Please guide.
Upvotes: 1
Views: 259
Reputation: 100209
Your mistake is that you are using stream intermediate operation filter
without calling the stream terminal operation. Read about the types of stream operations in official documentation. If you still want to use filter
(for learning purposes) you can solve your task with findAny()
or anyMatch()
:
boolean flag = lstRollNumbers.stream().filter(rn -> rn.equals(rollNumberToSearch))
.findAny().isPresent();
Or
boolean flag = lstRollNumbers.stream().filter(rn -> rn.equals(rollNumberToSearch))
.anyMatch(rn -> true);
Or don't use filter
at all (as @marstran suggests):
boolean flag = lstRollNumbers.stream().anyMatch(rn -> rn.equals(rollNumberToSearch));
Also note that method reference can be used here:
boolean flag = lstRollNumbers.stream().anyMatch(rollNumberToSearch::equals);
However if you want to use this not for learning, but in production code, it's much easier and faster to use good old Collection.contains
:
boolean flag = lstRollNumber.contains("3");
The contains method can be optimized according to the collection type. For example, in HashSet
it would be just hash lookup which is way faster than .stream().anyMatch(...)
solution. Even for ArrayList
calling contains
would be faster.
Upvotes: 7
Reputation: 28036
Use anyMatch
. It returns true
if any element in the stream matches the predicate:
String rollNumberToSearch = "3";
boolean flag = lstRollNumbers.stream().anyMatch(rn -> rn.equals(rollNumberToSearch));
Upvotes: 6