1

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.

1

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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));

1 Comment

And of course, as Tagir Valeev mentions, lstRollnumbers.contains(rollNumberToSearch) is better in this particular case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.