如何过滤动态嵌套列表对象Java 8 [英] How to filter dynamically nested list object java 8
问题描述
如何过滤动态嵌套列表对象Java 8
How to filter dynamically nested list 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),每个移动设备上都有多个计划.如何为每个移动设备动态过滤通用计划?
So, I have 3 mobiles (mobiles will be dynamic 3 or 4..etc) with multiple plans on each mobile device. How to dynamically filter common plan for each mobile device ?
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
中的一种用于获取所有手机通用计划的方法可能看起来像:
A method inside Items
to get all plans common to all mobiles might look like:
public List<Plan> getCommonPlans() {
return mobiles.stream().flatMap(Mobile::streamPlans).distinct()
.filter(p -> mobiles.stream().allMatch(m -> m.hasPlan(p)))
.collect(Collectors.toList());
}
这假定Mobile.streamPlans
和Mobile.hasPlan
方法非常简单.
this assumes Mobile.streamPlans
and Mobile.hasPlan
methods which are pretty trivial.
一种略有不同的方法,更有效,但可能不是那么直观,它是对计划进行计数,并过滤计数等于移动台数量的计划:
A slightly different method, more efficient but perhaps not so intuitive, is to count the plans and filter for ones that have counts equal to number of mobiles:
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());
这篇关于如何过滤动态嵌套列表对象Java 8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!