繁体   English   中英

如何过滤动态嵌套列表 object java 8

[英]How to filter dynamically nested list object java 8

如何过滤动态嵌套列表 object java 8

例子:

class Items {
    List<Mobile> mobiles;
}

class Mobile{
    String mName;
    List<Plans> plans;
}

class Plans{
    String planId;
    String planName;
}

所以,我有 3 部手机(手机将是动态的 3 或 4..etc),每个移动设备上有多个计划。 如何动态过滤每个移动设备的通用计划?

示例(P1-planId):
 Items: M1 - P1,P2,P3,P4 M2 - P4,P5,P6,P1,P8,P2 M3 - P7,P2,P4,P1,P8,P9,P10
结果:
 Items: M1 - P1,P2,P4 M2 - P1,P2,P4 M3 - P1,P2,P4

Items中获取所有手机通用的所有计划的方法可能如下所示:

public List<Plan> getCommonPlans() {
    return mobiles.stream().flatMap(Mobile::streamPlans).distinct()
        .filter(p -> mobiles.stream().allMatch(m -> m.hasPlan(p)))
        .collect(Collectors.toList());
}

这假设Mobile.streamPlansMobile.hasPlan方法非常简单。

一种稍微不同的方法,更有效但可能不那么直观,是计算计划并过滤计数等于手机数量的计划:

    return mobiles.stream().flatMap(Mobile::streamPlans)
        .collect(Collectors.groupingBy(m -> m, Collectors.counting())
        .entrySet().stream()
        .filter(e -> e.getValue() == mobiles.size())
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

首先,从该列表中获取第一部手机的计划并retainAll所有手机计划。

List<Plans> commonPlans = new ArrayList<>(mobiles.get(0).getPlans());
for (int i = 1; i < mobiles.size(); i++) {
  commonPlans.retainAll(mobiles.get(i).getPlans());
}

注意:确保覆盖PlansequalshashCode并检查空手机列表

稍微不同的方法是:

  • stream 所有Mobile
  • map 每个Mobile到其List<Plan> s
  • 创建所有计划的联合。

在代码中,这可能看起来像这样:

HashSet<Plan> initialSet = new HashSet<>(mobiles.get(0).getPlans());
return mobiles.stream()
    .map(Mobile::getPlans)
    .map(HashSet<Plan>::new)
    .reduce(initialSet, (plan1, plan2) -> { 
        plan1.retainAll(plan2);
        return plan1;
    });

Ideone 演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM