sneppets-java8

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) {
		this.id = id;
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

        public Long getId() {
                return id;
        }

        public void setId(Long id) {
                this.id = id;
        }


}

Example – Lambda Expression

package com.sneppets.app;

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");
		skillList.add(skill1);
		Skill skill2 = new Skill(2L, "Python");
		skillList.add(skill2);
		Skill skill3 = new Skill(3L, "Golang");
		skillList.add(skill3);
		
		String skill1Name = "C";		
		boolean cExists = skillList.stream().anyMatch(s -> s.getName().equals(skill1Name));
		System.out.println("C skill exists in collection ? : " + cExists);
		String skill2Name = "Java";		
		boolean jExists = skillList.stream().anyMatch(s -> s.getName().equals(skill2Name));
		System.out.println("Java skill exists in collection ? : " + jExists);
	}

}

Output

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

References

Leave a Reply

avatar
  Subscribe  
Notify of