【问题标题】:Java 8 Filter list based on condition from the part of the listJava 8 根据列表部分的条件过滤列表
【发布时间】:2019-05-29 23:33:21
【问题描述】:

我有一个对象列表 N,其中 N 是

N
|--- type (1,2,3)
|--- A (applicable if type 1)
|--- B (applicable if type 2)
|--- C (applicable if type 3)
|--- List<Integer> p 

现在,我想要的结果是 List 的过滤版本,这样:

create a list List<Integer> l

先这样做:

if(type == 1) && (A > some_value):
  Add all elements of p to l
  select this N

L 形成后:

if(type != 1)
  if(l contains any element from p):
    select this N

如何一步一步使用流来实现这一点?

我可以先过滤并创建一个列表“l”,然后使用该列表进行过滤。

l = stream.filter(a -> a.type == 1 && a.A > some_value).collect(..)

然后,使用 l 进一步过滤。

但是有没有更好更精确的方法呢?

【问题讨论】:

  • 您的数据结构可能不适合您需要执行的操作。这是来自第三方的数据结构还是您自己的数据结构。如果你能解释你的意图可能是最好的。

标签: java collections java-8 java-stream


【解决方案1】:
if(type == 1) && (A > some_value):
  Add all elements of p to l
  select this N

不知道这里的“选择这个 N”是什么意思,因为您选择的是 p 值,所以我忽略了该行。

Set<Integer> set = listOfN.stream()
    .filter(n -> n.type == 1 && n.A > some_value)
    .flatMap(n -> n.p.stream())
    .collect(Collectors.toSet());

为了更好地执行下一步 (contains()),结果是从 List 更改为 Set

if(type != 1)
  if(l contains any element from p):
    select this N
List<N> result = listOfN.stream()
    .filter(n -> n.type != 1 && n.p.stream().anyMatch(set::contains))
    .collect(Collectors.toList());

【讨论】:

  • 谢谢,但这样做只会让我得到 type != 1 的对象,对吧?我想要的是如果类型 1,然后检查 n.A > some_value,如果类型 = 2 或 3,。抱歉,如果没有明确提及这一点。
  • 另外,这两个步骤可以合并吗?
  • @sakura 您增强了第二块中的filter,使其也包含类型 1。 --- 可以在单个语句中完成,但这会严重影响性能!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
  • 2022-10-07
  • 2017-03-09
  • 1970-01-01
  • 2019-08-03
  • 2017-06-21
相关资源
最近更新 更多