Monday, December 4, 2017

Java 8 : Finding allMatch, noneMatch,anyMatch


How to find if (all/any/none) of the  elements of a collection meets a condition ?



package com.tvidushi.java8.match;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class MatchExamples {
public static void main(String[] args) {
_find();
_findAllMatch();
_findAnyMatch();
_findnoneMatch();
}
/*
* @return any/all/none matches
*
* */
public static void _find() {
Predicate<Integer> p = num -> num % 2 == 0;
List<Integer> list = Arrays.asList(32,501,24,7,17,19,24,34);
System.out.println("allMatch:" + list.stream().allMatch(p));
System.out.println("anyMatch:" + list.stream().anyMatch(p));
System.out.println("noneMatch:" + list.stream().noneMatch(p));
}
/**
* @return true if all elements matches a condition
*
* */
public static void _findAllMatch() {
List<Student> list = Student.getStudentList();
System.out.println("Do all Student names start with A : "+
Student.getStudentList()
.stream()
.allMatch(e -> e.name.startsWith("A")));
System.out.println("Have All Students pass the exam (pass marks :13) : "+
Student.getStudentList()
.stream()
.allMatch(e -> e.marks >=13));
}
/**
* @return true if any element matches a condition
*
* */
public static void _findAnyMatch() {
List<Student> list = Student.getStudentList();
System.out.println("Is there any student with name starting with (A) : "+
Student.getStudentList()
.stream()
.anyMatch(e -> e.name.startsWith("A")));
System.out.println("Is there any student with name starting with (Z) : "+
Student.getStudentList()
.stream()
.anyMatch(e -> e.name.startsWith("Z")));
}
/*
* nonematch
* @return true if no match is found
*
* */
public static void _findnoneMatch() {
System.out.println("Is there any Student with name starting with (Z) : "+
Student.getStudentList()
.stream()
.noneMatch( e -> e.name.startsWith("Z")));
System.out.println("Is there any Student with name starting with (A) : "+
Student.getStudentList()
.stream()
.noneMatch( e -> e.name.startsWith("A")));
}
static class Student {
public int rollno;
public String name;
public int marks;
public Student(int rollno,String name,int marks ){
this.rollno = rollno;
this.name = name;
this.marks = marks;
}
public static List<Student> getStudentList(){
return Arrays.asList(new Student(1, "Ayush", 20),
new Student(2, "Bob", 30),
new Student(3, "Catherine", 24),
new Student(4, "Dinesh", 21),
new Student(5, "Avinash", 20),
new Student(6, "Nash", 30),
new Student(7, "Sara", 34),
new Student(8, "Rob", 21));
}
}
}


No comments:

Post a Comment