使用多个过滤器使用 Java Stream 搜索列表

我有一个 Java 对象列表(假设 getter 和 setter):


Record(String name, String part, String value);

如果列表包含某个name值和某个值,我需要返回一个布尔part值。


我一次只为一个过滤器工作:


//assume records are added to this list

List<Record> masterList = new ArrayList<Record>();


boolean check = masterList.stream().map(Record::getName).filter(record.getName()::equals).findFirst().isPresent();

但是我对此尝试出错Non-static method cannot be referenced from a static context:Record::getPart


masterList.stream().map(Record::getName).filter(record.getName()::equals).map(Record::getPart).filter(record.getPart()::equals).findFirst().isPresent();


猛跑小猪
浏览 146回答 1
1回答

慕慕森

你试图做的事情是不可能的,即当你执行时,map(Record::getName)你有一个Stream<String>所有字符串都是记录名称的地方,之后的任何链接方法调用都仅基于记录名称。而是只使用一个filter:boolean check = masterList.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.filter(s -> s.getName().equals(record.getName()) &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s.getPart().equals(record.getPart()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.findFirst().isPresent();或更好地使用anyMatchboolean check = masterList.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.anyMatch(s -> s.getName().equals(record.getName()) &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s.getPart().equals(record.getPart()));编辑:如果它可以是一个记录匹配名称,另一个记录匹配部分?然后您可以将所有记录名称和部分收集到一个集合中,如下所示:Set<String> container = masterList.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .flatMap(r -> Stream.of(r.getName(), r.getPart()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(toSet());然后做:boolean result = container.contains(record.getName()) &&&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;container.contains(record.getPart()) ;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java