【问题标题】:Retrieve a list of children of a unique class given a list of parents在给定父母列表的情况下检索唯一类的孩子列表
【发布时间】:2015-12-14 11:24:50
【问题描述】:

所以,假设我有一个父要素类。然后是该类的一堆孩子,例如 Dotted、Stripped、Blank,都继承自 Feature。

给定List<Feature>,我想获取该列表中属于 Dotted 类的所有对象。

仅供参考,我首先用features.add(New Dotted())features.add(New Blank())features.add(New Blank()) 等填充List<Feature> features...

我尝试过类似的方法:

public List<Dotted> getAllDotted(List<Feature> features){
    List<Dotted> result = features.stream().filter(o -> o.getClass().equals(Dotted.class)).collect(Collectors.toList());
    return result;
}

但它不起作用,因为 Collector.ToList() 不会将 filter() 的结果转换为 List&lt;Dotted&gt;

【问题讨论】:

    标签: java list filter collectors


    【解决方案1】:

    你可以这样做:

    List<Dotted> d = f.stream().filter(o -> o instanceof Dotted).map(o -> (Dotted) o).collect(Collectors.toList());
    

    可能不是很干净。

    【讨论】:

    • 好吧,这行得通,我读过关于 map() 的东西,我想也许与它有关,但现在没有。我对 Java 8 查询列表的方式非常陌生。从你的 POV 看,有什么不干净的地方?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 2020-05-26
    • 1970-01-01
    • 2021-08-24
    • 2022-11-12
    • 2017-05-19
    相关资源
    最近更新 更多