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 Value {
public String getValue() {
return value;
}
}
想得到List<List<String>>
-(包含值的实体列表)
这让我很累,但它只返回列表
obj.getEntities().stream()
.map(m -> m.getFields())
.flatMap(o -> o.stream())
.map( k -> k.getValues().get(0).getValue())
.collect(Collectors.toList());
这是可行的,但看起来不太好
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());
最佳答案
您可以通过将函数提取到变量中来使其更具可读性:
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());
如果需要,您可以使用 o -> o.getValues().get(0).getValue()
执行相同的操作,而不是使用一个复杂的 lambda,而是使用三个简单的 lambda。
关于lambda - 使用 flatMap 将三重列表转换为双重列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45913752/