谓词链接问题

发布于 2024-11-09 11:17:21 字数 348 浏览 5 评论 0原文

下面是对象结构 -

  • A 具有类 B 的集合,
  • B 与类 C 具有一对一映射code>
  • 我在 C 中定义了一个谓词 P

要求:返回一个 B 列表,其中至少有一个 C 元素 的谓词 P 返回 true

我当前的解决方案有一个 for 循环。我想知道是否可以在不使用 for 循环的情况下完成此操作。

Below is the object structure -

  • class A has a collection of class B
  • class B has one to one mapping with class C
  • I have a predicate P defined in C

Requirement : Return a list of B which have atleast one of the elements of C's Predicate P return true .

My current solution has a for loop. I was wondering if this can be done without using a for loop.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

奈何桥上唱咆哮 2024-11-16 11:17:21

为什么谓词的定义位置很重要?您的意思是它是在 C 上定义的吗?

// You already have Predicate<C> defined somewhere
Predicate<C> csPredicate = new Predicate<C>() {
    public boolean apply(C c) {
        return someComputationOn(c);
    }
};

Iterables.filter(A.getIterableOfB(), 
    Predicates.compose(
        csPredicate, 
        new Function<B, C>() {
            @Override
            public C apply(B b) {
                return b.getC();
            }
}));

我的答案与 sMoZely (+1) 非常相似,除了我使用 Iterables.filter() 并组成谓词而不是使用 Collections2,但想法是相同的。我也可能在问题中遗漏了一些东西......

Why does it matter where the Predicate is defined? Do you mean that it's define on C?

// You already have Predicate<C> defined somewhere
Predicate<C> csPredicate = new Predicate<C>() {
    public boolean apply(C c) {
        return someComputationOn(c);
    }
};

Iterables.filter(A.getIterableOfB(), 
    Predicates.compose(
        csPredicate, 
        new Function<B, C>() {
            @Override
            public C apply(B b) {
                return b.getC();
            }
}));

My answer is very similar to sMoZely (+1) except i'm using Iterables.filter() and composing the Predicates instead of using Collections2 but the idea is the same. I may also be missing something in the question...

二货你真萌 2024-11-16 11:17:21

如果我理解正确的话……你不能为 B 创建一个谓词来调用 C 的谓词吗?

即在 B 中...

new Predicate<B>() {
  @Override
  public boolean apply(B record) {
    return new PredicateOverC().apply(record.getC())
  }
}

然后在 A 中,您可以对 B 的集合和这个新谓词使用 Collections2.filter 吗?

If I understand this correctly ... can't you just create a Predicate for B that calls the Predicate for C?

i.e. in B ...

new Predicate<B>() {
  @Override
  public boolean apply(B record) {
    return new PredicateOverC().apply(record.getC())
  }
}

And then in A you can just use Collections2.filter over the collection of B and this new predicate?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文