如何从2个流Java中的1个流中查找anyMatch

时间:2019-07-17 20:54:38

标签: java java-8 java-stream

我正在尝试过滤一个流以从另一个流中获取anyMatch,并且由于某种原因,例如它与第二个流中的第二个元素不进行比较 我有那个结构

class TicketingDocumentInfo{
      private TicketingDocument;

      getDocument();
}

class TicketingDocument{
      private List<TicketingDocumentCoupon> coupons;
      getCoupons();
} 

class TicketingDocumentCoupon{
      private List<String> Id;  <--- only one string can be here so it's like just String
      getRefsId();
}

样本数据:

TicketingDocumentInfo doc = new TicketingDocumentInfo(new TicketingDocument(new List().add(new TicketingDocumentCoupon("SVC-1"))))
List<TicketingDocumentInfo> docsToMatch = new List(  
new TicketingDocumentInfo(new TicketingDocument(new List().add(new TicketingDocumentCoupon("SVC-2"),  
new TicketingDocumentInfo(new TicketingDocument(new List().add(new TicketingDocumentCoupon("SVC-1"))

我希望得到docsToMatch [1] 但是我收到空值,所以它与第二个元素没有比较

当前阶段:

 return ancillaries.stream()
                .filter(coupon -> coupon.getDocument().getCoupons().stream()
                        .flatMap(e -> e.getServiceItemRefIds().stream())
                        .anyMatch( c -> aeroDoc.getDocument().getCoupons().stream()
                                .flatMap(secondCoupon -> secondCoupon.getServiceItemRefIds().stream()).toString().contains(c)))
                .findFirst();

测试:

Set<String> test = aeroDoc.getDocument().getCoupons().stream()
                .flatMap(coupon -> coupon.getServiceItemRefIds().stream())
                .collect(Collectors.toSet());
        System.out.println("1 " + test.toString());
        Set<String> test2 = ancillaries.stream()
                .flatMap( d -> d.getDocument().getCoupons().stream())
                .flatMap( g -> g.getServiceItemRefIds().stream())
                .collect(Collectors.toSet());
        System.out.println("2 "+test2.toString());


        return ancillaries.stream()
                .filter(coupon -> coupon.getDocument().getCoupons().stream()
                        .flatMap(e -> e.getServiceItemRefIds().stream())
                        .anyMatch( c -> aeroDoc.getDocument().getCoupons().stream()
                                .flatMap(secondCoupon -> secondCoupon.getServiceItemRefIds().stream()).toString().contains(c)))
                .findFirst();

测试输出:

1 [SVC-1]
2 [SVC-2, SVC-1]

1 个答案:

答案 0 :(得分:0)

必须添加.collect(Collectors.toSet())

return ancillaries.stream()
                .filter(coupon -> coupon.getDocument().getCoupons().stream()
                        .flatMap(e -> e.getServiceItemRefIds().stream())
                        .anyMatch( c -> aeroDoc.getDocument().getCoupons().stream()
                                .flatMap(secondCoupon -> secondCoupon.getServiceItemRefIds().stream()).collect(Collectors.toSet()).contains(c)))
                .findFirst();

``