列表中列表的Java 8流过滤值 [英] Java 8 Stream filtering value of list in a list

查看:232
本文介绍了列表中列表的Java 8流过滤值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像下面的对象

I have a an object which looks like the following

class MyObject {

    String type;
    List<String> subTypes;

}

给定MyObject的列表是否可以使用Java 8流对类型和子类型进行过滤?

Is it possible, given a list of MyObject's to use Java 8 streams to filter on both the type and then the subtype?

到目前为止,我已经拥有

So far I have

myObjects.stream()
    .filter(t -> t.getType().equals(someotherType)
    .collect(Collections.toList());

但是在此我还希望在每个的子类型上使用另一个过滤器来过滤特定子类型上的过滤器.我不知道该怎么做.

but within this I also want another filter on each of the subTypes filtering those on a particular subtype too. I can't figure out how to do this.

一个例子是

myObject { type: A, subTypes [ { X, Y, Z } ] }
myObject { type: B, subTypes [ { W, X, Y } ] }
myObject { type: B, subTypes [ { W, X, Z } ] }
myObject { type: C, subTypes [ { W, X, Z } ] }

我将传入matchType B和subType Z,所以我希望得到一个结果-> myObject类型B,子类型:W,X,Z

I would pass in matchType B and subType Z, so I would expect one result -> myObject type B, subtypes: W, X, Z

以下当前返回列表中的2个项目.

the following currently returns 2 items in a list.

myObjects.stream()
    .filter(t -> t.getType().equals("B")
    .collect(Collectors.toList());

但是我想在每个子类型上添加一个额外的过滤器,并且仅在存在"Z"的地方进行匹配.

but I would like to add an additional filter over the each of the subtypes and only matching where 'Z' is present.

推荐答案

您可以这样做:

myObjects.stream()
         .filter(t -> t.getType().equals(someotherType) && 
                      t.getSubTypes().stream().anyMatch(<predicate>))
         .collect(Collectors.toList());

这将获取

  • 满足有关type成员的条件.
  • 嵌套的List<String>中包含满足其他条件的对象,用<predicate>
  • 表示
  • meet a criteria regarding the type member.
  • contain objects in the nested List<String> that meet some other criteria, represented with <predicate>

这篇关于列表中列表的Java 8流过滤值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆