加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Stream:过滤子项,返回父项

发布时间:2020-12-15 04:48:14 所属栏目:Java 来源:网络整理
导读:假设一个类MyClass: public class MyClass { private final Integer myId; private final String myCSVListOfThings; public MyClass(Integer myId,String myCSVListOfThings) { this.myId = myId; this.myCSVListOfThings = myCSVListOfThings; } // Gette
假设一个类MyClass:

public class MyClass {

    private final Integer myId;
    private final String myCSVListOfThings;

    public MyClass(Integer myId,String myCSVListOfThings) {
        this.myId = myId;
        this.myCSVListOfThings = myCSVListOfThings;
    }

    // Getters,Setters,etc
}

这个流:

final Stream<MyClass> streamOfObjects = Stream.of(
        new MyClass(1,"thing1;thing2;thing3"),new MyClass(2,"thing2;thing3;thing4"),new MyClass(3,"thingX;thingY;thingZ"));

我想在myCSVListOfThings中返回包含条目“thing2”的MyClass的每个实例.

如果我想要一个List< String>包含myCSVListOfThings可以很容易地完成:

List<String> filteredThings = streamOfObjects
        .flatMap(o -> Arrays.stream(o.getMyCSVListOfThings().split(";")))
        .filter("thing2"::equals)
        .collect(Collectors.toList());

但我真正需要的是List< MyClass>.

这就是我现在所拥有的:

List<MyClass> filteredClasses = streamOfObjects.filter(o -> {
     Stream<String> things = Arrays.stream(o.getMyCSVListOfThings().split(";"));
     return things.anyMatch(s -> s.equals("thing2"));
}).collect(Collectors.toList());

但不知怎的,它感觉不对.比在Predicate中打开一个新的Stream更清洁的解决方案?

解决方法

首先,我建议你为MyClass public boolean containsThing(String str)添加额外的方法,这样你就可以像这样转换代码:

List<MyClass> filteredClasses = streamOfObjects
  .filter(o -> o.containsThing("thing2"))
  .collect(Collectors.toList());

现在您可以根据需要实现此方法取决于输入数据:拆分为Stream,拆分为Set,甚至搜索子字符串(如果可能且有意义),如果需要则缓存结果.

您对此类的使用了解得更多,因此您可以做出正确的选择.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读