Check if Element exists in a Collection using Lambda Expressions

If you wanted to check whether element exists in a collection or not using specific id or name, the better approach is to use anyMatch() method of Stream interface of Lambda Expressions.

Lambda Expressions – Check if Element exists in a Collection

The example below shows how to use anyMatch() method to check whether any elements of the stream match the provided predicate. The predicate will not be evaluated if the stream is empty.

public class Skill {
	private String name;
        private Long id;
	public Skill() {
	public Skill(Long id, String name) { = id; = name;

	public String getName() {
		return name;

	public void setName(String name) { = name;

        public Long getId() {
                return id;

        public void setId(Long id) {
       = id;


Example – Lambda Expression


import java.util.ArrayList;
import java.util.List;

import com.sneppets.domain.Skill;
public class LambdaExample {
	public static void main (String[] args) {
		List<Skill> skillList = new ArrayList<>();
		Skill skill1 = new Skill(1L, "Java");
		Skill skill2 = new Skill(2L, "Python");
		Skill skill3 = new Skill(3L, "Golang");
		String skill1Name = "C";		
		boolean cExists = -> s.getName().equals(skill1Name));
		System.out.println("C skill exists in collection ? : " + cExists);
		String skill2Name = "Java";		
		boolean jExists = -> s.getName().equals(skill2Name));
		System.out.println("Java skill exists in collection ? : " + jExists);



C skill exists in collection ? : false
Java skill exists in collection ? : true

java.util.Stream Notes

  • A stream is not a data structure that stores elements, but it just takes the elements from a source, for example an array.
  • Any operation that you perform on stream produces a result without modifying its source.
  • It is unbounded unlike collections.
  • The elements of stream are visited only once during the life of stream.

Advantages of Lambda Expressions

  • Conciseness
  • Readability
  • Reduction in code inflate.
  • Code reuse.
  • Functional Programming – programming using expressions.

Further Learning


Notify of

Inline Feedbacks
View all comments