【有书共读】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");
}

#Java##笔记##读书笔记#
全部评论

相关推荐

01-12 17:45
门头沟学院 Java
叁六玖:这样的应该钱不多,以前我也被问,我在问他们实习公工资多少,一般都是2200-2800
找实习记录
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务