【有书共读】Java攻略 读书笔记09
Predicate接口主要用于流的筛选,给定一个包含若干项的流,Stream接口的filter方法传入Predicate并返回一个新的流,它包含了满足给定谓词的项。
Predicate接口包含的单一抽象方法为boolean test(T t),它传入一个泛型参数并返回true或false.
给定一个名称集合,可以通过流处理找出所有具有特定长度的实例
//查找具有给定长度的字符串
public String getNameOfLength(int length,String... names){
return Arrays.stream(names)
.filter(s -> s.length() == length)
.collect(Collectors.joining(","));
}
//查找以给定字符串开头的字符串
public String getNameStartingWith(String s,String... names){
return Arrays.stream(names)
.filter(str -> str.startsWith(s))
.collect(Collectors.joining(","));
}
//查找满足任意谓词的字符串
public class ImplementPredicate{
public String getNamesStatisfyingCondition(
Predicate<String> condition, String... names){
return Arrays.stream(names)
.filter(condition)
.collect(Collectors.joining(","));
}
}
//为常见情况添加常量
public class ImplementPredicate{
public static final Predicate<String> LENGTH_FIVE =
s-> s.length() == 5;
public static final Predicate<String> STARTS_WITH_S =
s-> s.startsWith("S");
}
查看26道真题和解析