处理多层list嵌套
方式如下:
@Data
public class C {
private String name;
}
@Data
public class B {
private List<C> cList;
}
@Data
public class A {
private String name;
private List<B> bList;
}
public class Test {
public static void main(String[] args) {
A a1 = new A("a1");
A a2 = new A("a2");
A a3 = new A("a3");
// 具体的list数据准备,此处省略
......
List<A> aList = Lists.newArrayList(a1, a2, a3);
// 筛选出A.name="a1", C对象的name属性。
List<String> nameList = Optional.ofNullable(aList).orElse(Lists.newArrayList()).stream()
.filter(a -> Objects.equals("a1", a.getName())).flatMap(a -> a.getBList().stream())
.flatMap(b -> b.getCList().stream()).map(C::getName).collect(Collectors.toList());
// 代码纯手写,没有编译或者跑一下,若有问题,需自己改下。
}
}
按某种属性分类
@Data
public class B {
private String bName;
private String bCode;
private String bizType;
}
@Data
public class A {
private String aName;
private String aCode;
private List<B> bList;
}
public class Test() {
public static void main(String[] args) {
A a = new A();
// 根据bizType对B对象分类
Map<String, List<B>> resultMap = a.getBList().stream().collect(Collectors.groupingBy(B::getBizType))
}
}