文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

浅谈Java8新特性Predicate接口

2024-04-02 19:55

关注

一、前言

Java 8中引入了Predicate功能接口。

Java Predicate表示一个参数的谓词。

Predicate是一个布尔值的函数。

Java Predicate是一个功能接口,属于java.util.function包。

Predicate的功能方法是test(T t)

Predicate的其他方法是testisEqualandornegatenot

not方法在Java 11中被引入。

在本文章,我们将提供Predicate的例子及其所有方法。

二、test(T t)


boolean test(T t) 

testPredicate的功能方法。它在给定的参数上评估这个谓词。

例1:

PredicateTestDemo1.java


import java.util.function.Predicate;
public class PredicateTestDemo1 {
  public static void main(String[] args) {
	// Is username valid
	Predicate<String> isUserNameValid = u -> u != null && u.length() > 5 && u.length() < 10;
	System.out.println(isUserNameValid.test("Mahesh")); //true

	// Is password valid
	Predicate<String> isPasswordValid = p -> p != null && p.length() > 8 && p.length() < 15;
	System.out.println(isPasswordValid.test("Mahesh123")); //true
	
	// Word match
	Predicate<String> isWordMatched = s -> s.startsWith("Mr.");
	System.out.println(isWordMatched.test("Mr. Mahesh")); //true
	
	//Odd numbers
	Predicate<Integer> isEven = n -> n % 2 == 0;
	for(int i = 0 ; i < 5 ; i++) {
	  System.out.println("Is "+ i + " even: " + isEven.test(i));
	}
  }
} 

输出结果

true
true
true
Is 0 even: true
Is 1 even: false
Is 2 even: true
Is 3 even: false
Is 4 even: true

例2:

PredicateTestDemo2.java


import java.util.function.Function;
import java.util.function.Predicate;
public class PredicateTestDemo2 {
  public static void main(String[] args){
    Predicate<Student> maleStudent = s-> s.getAge() >= 20 && "male".equals(s.getGender());
    Predicate<Student> femaleStudent = s-> s.getAge() > 18 && "female".equals(s.getGender());
    
    Function<Student,String> maleStyle = s-> "Hi, You are male and age "+s.getAge();
    Function<Student,String> femaleStyle = s-> "Hi, You are female and age "+ s.getAge();
    
    Student s1 = new Student("Gauri", 20,"female");
    if(maleStudent.test(s1)){
        System.out.println(s1.customShow(maleStyle));
    }else if(femaleStudent.test(s1)){
        System.out.println(s1.customShow(femaleStyle));
    }      
  } 

Student.java


import java.util.function.Function;
public class Student {
  private String name;
  private int age;
  private String gender;
  private int marks;
  public Student(String name, int age, String gender){
    this.name = name;	
    this.age = age;
    this.gender = gender;
  }  
  public Student(String name, int age, String gender, int marks){
    this.name = name;
    this.age = age;
    this.gender = gender;
    this.marks = marks;
  }
  public String getName() {
    return name;
  }
  public int getAge() {
    return age;
  }
  public String getGender() {
    return gender;
  }
  public int getMarks() {
    return marks;
  }
  public  String customShow(Function<Student,String> fun){
    return fun.apply(this);
  }
  public String toString(){ 
    return name+" - "+ age +" - "+ gender + " - "+ marks;  
  }  
} 

输出结果

Hi, You are female and age 20

三、and(Predicate<? super T> other)


default Predicate<T> and(Predicate<? super T> other) 

andPredicate的默认方法,它返回一个组成的谓词,表示这个谓词和其他谓词的短路逻辑AND。在评估组成的谓词时,如果这个谓词是假的,那么其他谓词将不会被评估。在错误的情况下,如果此谓词抛出错误,那么其他谓词将不会被评估。

PredicateAndDemo.java


import java.util.function.Predicate;
public class PredicateAndDemo {
  public static void main(String[] args) {
	Predicate<Student> isMaleStudent = s -> s.getAge() >= 20 && "male".equals(s.getGender());
	Predicate<Student> isFemaleStudent = s -> s.getAge() > 18 && "female".equals(s.getGender());
	Predicate<Student> isStudentPassed = s -> s.getMarks() >= 33;

	// Testing if male student passed.
	Student student1 = new Student("Mahesh", 22, "male", 30);
	Boolean result = isMaleStudent.and(isStudentPassed).test(student1);
	System.out.println(result); //false

	// Testing if female student passed.
	Student student2 = new Student("Gauri", 19, "female", 40);
	result = isFemaleStudent.and(isStudentPassed).test(student2);
	System.out.println(result); //true
  }
} 

输出

false
true

四、or(Predicate<? super T> other)


default Predicate<T> or(Predicate<? super T> other)

orPredicate的默认方法,它返回一个组成的谓词,表示此谓词和其他谓词的短路逻辑OR。在评估组成的谓词时,如果此谓词为真,那么其他谓词将不会被评估。在错误的情况下,如果此谓词抛出错误,那么其他谓词将不会被评估。

PredicateOrDemo.java


import java.util.function.Predicate;
public class PredicateOrDemo {
  public static void main(String[] args) {
	Predicate<Student> isMaleStudent = s -> s.getAge() >= 20 && "male".equals(s.getGender());
	Predicate<Student> isFemaleStudent = s -> s.getAge() > 18 && "female".equals(s.getGender());
	Predicate<Student> isStudentPassed = s -> s.getMarks() >= 33;

	Student student1 = new Student("Mahesh", 22, "male", 35);
	//Test either male or female student
	Boolean result = isMaleStudent.or(isFemaleStudent).test(student1);
	System.out.println(result); //true
	//Is student passed, too
	result = isMaleStudent.or(isFemaleStudent).and(isStudentPassed).test(student1);
	System.out.println(result); //true
  }
} 

输出

true
true

五、negate()


default Predicate<T> negate() 

negatePredicate的默认方法,它返回一个表示该谓词的逻辑否定的谓词。如果评估的结果是真的,negate将使它变成假的,如果评估的结果是假的,negate将使它变成真的。

PredicateNegateDemo.java


import java.util.function.Predicate;
public class PredicateNegateDemo {
  public static void main(String[] args) {
       Predicate<Integer> isNumberMatched = n -> n > 10 && n < 20;
       //With negate()
       Boolean result = isNumberMatched.negate().test(15);
       System.out.println(result); //false
       
       //Without negate()
       result = isNumberMatched.test(15);
       System.out.println(result); //true
       
       Predicate<String> isValidName = s -> s.length() > 5 && s.length() < 15;
       System.out.println(isValidName.negate().test("Krishna")); //false
       
       Predicate<Integer> isLessThan50 = n -> n < 50;
       System.out.println(isLessThan50.negate().test(60)); //true
       
       Predicate<Integer> isGreaterThan20 = n -> n > 20;
       System.out.println(isGreaterThan20.negate().test(30));  //false   
       
       result = isLessThan50.and(isGreaterThan20).negate().test(25);
       System.out.println(result); //false
  }
} 

输出

false
true
false
true
false
false

六、isEqual(Object targetRef)


static <T> Predicate<T> isEqual(Object targetRef) 

isEqualPredicate的静态方法,它返回测试两个参数是否等于Objects.equals(Object, Object)的谓词。我们使用Predicate.isEqual创建predicate,如下所示。


Predicate<String> isHelloMsg = Predicate.isEqual("Hello");
Predicate<Book> isMahabharatBook = Predicate.isEqual(new Book("Mahabharat", "Vyas")); 

PredicateIsEqualDemo.java


import java.util.function.Predicate;
public class PredicateIsEqualDemo {
  public static void main(String[] args) {
    System.out.println("---Testing Hello message---");	
    Predicate<String> isHelloMsg = Predicate.isEqual("Hello");
    System.out.println(isHelloMsg.test("Hello")); //true
    System.out.println(isHelloMsg.test("Hi"));  //false
    
    System.out.println("---Testing Mahabharat book---");
    Book mahabharatBook = new Book("Mahabharat", "Vyas");
    Predicate<Book> isMahabharatBook = Predicate.isEqual(mahabharatBook);
    System.out.println(isMahabharatBook.test(new Book("Mahabharat", "Vyas"))); //true
    System.out.println(isMahabharatBook.test(new Book("Ramayan", "Valmiki"))); //false
  }
}

class Book {
  private String name;
  private String writer;
  public Book(String name, String writer) {
	this.name = name;
	this.writer = writer;
  }
  public String getName() {
    return name;
  }
  public String getWriter() {
    return writer;
  }
  public boolean equals(final Object obj) {
    if (obj == null) {
        return false;
    }
    final Book b = (Book) obj;
    if (this == b) {
        return true;
    } else {
        return (this.name.equals(b.name) && (this.writer == b.writer));
    }
  }  
} 

输出

---Testing Hello message---
true
false
---Testing Mahabharat book---
true
false

七、not(Predicate<? super T> target)


static <T> Predicate<T> not(Predicate<? super T> target) 

notJava 11中引入的Predicate的静态方法。

not返回的predicate是对所提供的predicate的否定。

这是通过返回调用target.negate()的结果来完成的。

找到Predicate.not的例子。

PredicateNotDemo.java


import java.util.function.Predicate;
public class PredicateNotDemo {
  public static void main(String[] args) {
    Predicate<Integer> isOdd = n -> n % 2 == 1;
    Predicate<Integer> isEven = Predicate.not(isOdd);
    System.out.println(isEven.test(10)); //true
    
    Predicate<String> isNotHelloMsg = Predicate.not(Predicate.isEqual("Hello"));
    System.out.println(isNotHelloMsg.test("Hi")); //true
    System.out.println(isNotHelloMsg.test("Hello")); //false
  }
} 

输出

true
true
false

在Stream中使用Predicate 

我们将提供例子在Stream中使用Predicate

我们将使用Stream.filter来过滤列表。

filter()的语法如下。


filter(Predicate predicate)

filter()在处理给定的Predicate后,返回由过滤后的数据组成的Stream实例。

例1:

PredicateStreamDemo1.java


import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class PredicateStreamDemo1 {
  public static void main(String[] args) {
	List<String> list = new ArrayList<>();	
	list.add("Vijay");
	list.add("Ramesh");
	list.add("Mahesh");
	
	Predicate<String> isNameEndsWithSh = s -> s.endsWith("sh");
	
	list.stream().filter(isNameEndsWithSh)
	  .forEach(s -> System.out.println(s));
  }
} 

输出

Ramesh
Mahesh

例2:

PredicateStreamDemo2.java


import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateStreamDemo2 {
  public static void main(String[] args) {
	List<Student> list = new ArrayList<>();
	list.add(new Student("Mahesh", 20, "male", 38));
	list.add(new Student("Gauri", 21, "female", 45));	
	list.add(new Student("Krishna", 19, "male", 42));
	list.add(new Student("Radha", 20, "female", 35));
	
	System.out.println("--- All students scoring marks > 40 ---");
	Predicate<Student> isScoreGt40 = std -> std.getMarks() > 40;
	filterStudent(isScoreGt40, list).forEach(s -> System.out.println(s));
	
	System.out.println("--- All Male Students ---");
	Predicate<Student> isMaleStudent = std -> "male".equals(std.getGender());
	filterStudent(isMaleStudent, list).forEach(s -> System.out.println(s));
	
	System.out.println("--- All Female Students ---");
	Predicate<Student> isFemaleStudent = std -> "female".equals(std.getGender());
	filterStudent(isFemaleStudent, list).forEach(s -> System.out.println(s));	
	
	System.out.println("--- All Female Students scoring > 40 ---");
	filterStudent(isFemaleStudent.and(isScoreGt40), list).forEach(s -> System.out.println(s));		
  }
  
  static List<Student> filterStudent(Predicate<Student> predicate, List<Student> list) {
	return list.stream().filter(predicate).collect(Collectors.toList());
  }
} 

输出

--- All students scoring marks > 40 ---
Gauri - 21 - female - 45
Krishna - 19 - male - 42
--- All Male Students ---
Mahesh - 20 - male - 38
Krishna - 19 - male - 42
--- All Female Students ---
Gauri - 21 - female - 45
Radha - 20 - female - 35
--- All Female Students scoring > 40 ---
Gauri - 21 - female - 45

到此这篇关于浅谈Java8新特性Predicate接口的文章就介绍到这了,更多相关Java Predicate内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯