调节 java 流的过滤器

我正在研究一个过滤器函数,它可以使用许多参数进行过滤,为此我正在使用 Java Streams。这就是我的代码:


public void filter(String cours,String prof,String salle,String group) {


this.appointments().addAll(getTimeTable().getCreneauxsList().stream()

            .filter(e->e.getProf().equalsIgnoreCase(prof) )

            .filter(e->e.getCours().equalsIgnoreCase(cours) )

            .filter(e->e.getSalle().equalsIgnoreCase(salle) )

            .filter(e->e.getGroup().equalsIgnoreCase(group) )

            .collect(Collectors.toList()));

}

我想查看一个或多个参数 cours、salle、prof、group 是否为 null 或其 trim () = "",用它过滤是不值得的,因为结果不是我期望得到的。


但我不知道该怎么做。


Cats萌萌
浏览 220回答 3
3回答

大话西游666

您可以创建一个方法来在过滤期间处理 null 或空字符串,如下所示:public static boolean compareNullableString(String str, String filterStr) {    return (filterStr == null || filterStr.trim().equals("")) ? true : filterStr.equalsIgnoreCase(str);}然后修改你的代码,如:this.appointments().addAll(getTimeTable().getCreneauxsList().stream()                .filter(e->compareNullableString(e.getProf,prof) )                .filter(e->compareNullableString(e.getCours,cours))                .filter(e->compareNullableString(e.getSalle,salle) )                .filter(e->compareNullableString(e.getGroup,group) )                .collect(Collectors.toList()));

炎炎设计

您可以Strings.isNullOrEmpty()从番石榴中使用:boolean isNullOrEmpty = Strings.isNullOrEmpty(e.getProf());或者有一组来自 apache commons 的方法:StringUtils.isBlank, StringUtils.isNotBlank, StringUtils.isEmpty, StringUtils.isNotEmpty这可能有用:StringUtils.isBlank() 与 String.isEmpty()您的情况isNotBlank正是您正在寻找的:BiPredicate<String, String> myPredicate = (field, eqString) ->&nbsp; &nbsp; &nbsp; &nbsp; StringUtils.isNotBlank(field) && field.equalsIgnoreCase(eqString);&nbsp; &nbsp; ...&nbsp; &nbsp; .filter(e -> myPredicate.test(e.getProf(), prof))&nbsp; &nbsp; .filter(e -> myPredicate.test(e.getCours(), cours))&nbsp; &nbsp; .filter(e -> myPredicate.test(e.getSalle(), salle))&nbsp; &nbsp; .filter(e -> myPredicate.test(e.getGroup(), group))&nbsp; &nbsp; ...

MYYA

这个答案可以改进。方法compareNullableString可以按原样。您可以摆脱创建 List 并在forEach. 过滤也可以提取到Predicate。List<String> appointments = this.appointments();Stream<Predicate<Creneauxs>> filterStream = Stream.of(&nbsp; &nbsp; &nbsp; &nbsp; e->compareNullableString(e.getProf,prof),&nbsp; &nbsp; &nbsp; &nbsp; e->compareNullableString(e.getCours,cours),&nbsp; &nbsp; &nbsp; &nbsp; e->compareNullableString(e.getSalle,salle),&nbsp; &nbsp; &nbsp; &nbsp; e->compareNullableString(e.getGroup,group));Predicate<Creneauxs> filter = filterStream.reduce(Predicate::and).orElse(x->false);getTimeTable().getCreneauxsList().stream()&nbsp; .filter(filter)&nbsp; .forEach(appointments::add);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java