Lambda 使用flatMap将三重列表转换为双列表
POJO看起来像这样:Lambda 使用flatMap将三重列表转换为双列表,lambda,java-8,java-stream,Lambda,Java 8,Java Stream,POJO看起来像这样: public class Obj { List<Entities> entities; } public class Entities { List<Fields> fields; } public class Fields { List<Value> values; //Get only first member : values.get(0)!!!! } public class V
public class Obj {
List<Entities> entities;
}
public class Entities {
List<Fields> fields;
}
public class Fields {
List<Value> values; //Get only first member : values.get(0)!!!!
}
public class Value {
public String getValue() {
return value;
}
}
这是工作,但看起来不好
List<List<String>> s1 = obj.getEntities().stream()
.map(m -> m.getFields().stream()
.map(o -> o.getValues().get(0).getValue())
.collect(Collectors.toList()) )
.collect(Collectors.toList());
List s1=obj.getEntities().stream()
.map(m->m.getFields().stream())
.map(o->o.getValues().get(0.getValue())
.collect(收集器.toList())
.collect(Collectors.toList());
我说不出你为什么觉得这样不好,我只能这样想,但它几乎没有更好的地方,可能更具可读性:
obj.getEntities().stream()
.flatMap(e -> Stream.of(e.getFields().stream()
.map(f -> f.getValues().get(0).getValue())))
.collect(Collectors.mapping(
x -> x.collect(Collectors.toList()),
Collectors.toList()));
通过将函数提取到变量中,可以使其更具可读性:
Function<Entities, List<String>> extractFirstFieldsValues = m -> m.getFields().stream()
.map(o -> o.getValues().get(0).getValue())
.collect(Collectors.toList());
List<List<String>> s1 = obj.getEntities().stream()
.map(extractFirstFieldsValues)
.collect(Collectors.toList());
函数extractFirstFieldsValues=m->m.getFields().stream()
.map(o->o.getValues().get(0.getValue())
.collect(Collectors.toList());
列表s1=obj.getEntities().stream()
.map(ExtractFirstFields值)
.collect(Collectors.toList());
如果需要,您可以使用o->o.getValues().get(0).getValue()
执行相同的操作,而不是使用一个复杂的lambda,而是使用三个简单的lambda
Function<Entities, List<String>> extractFirstFieldsValues = m -> m.getFields().stream()
.map(o -> o.getValues().get(0).getValue())
.collect(Collectors.toList());
List<List<String>> s1 = obj.getEntities().stream()
.map(extractFirstFieldsValues)
.collect(Collectors.toList());