英文:
Java 8 iterate nested loop and fetch details
问题
public class Data {
private List<SubscriberList> subscriberCriteriaList;
}
public class SubscriberList {
private String mdn;
private List<SubscriberCriteriaList> subscriberCriteriaList;
}
public class SubscriberCriteriaList {
private String status;
private String msg;
}
{
"subscriberList": [
{
"mdn": "string",
"subscriberCriteriaList": [
{
"status": "FAIL",
"msg": "error message"
}
]
}
]
}
英文:
I have a model object which contains nested arrays and i want to retrieve some details within that model .How to collect property msg from subscriberCriteriaList into an array where subscriberCriteriaList.status is FAIL. I would expect java 8 solution for the same ? Below is the sample model objects and the corresponding json structure .
public class Data{
private List<subscriberList> subscriberCriteriaList;
}
public class subscriberList{
private String mdn;
private List<SubscriberCriteriaList> subscriberCriteriaList;
}
public class SubscriberCriteriaList{
private String status;
private String msg;
}
Sample json structure
{
"subscriberList": [
{
"mdn": "string",
"subscriberCriteriaList": [
{
"status": "FAIL",
"msg": "error message"
}
]
}
]
}
答案1
得分: 1
假设顶层对象的类型为 Data
,并且所有提及的类中都有适当的获取器(getter),可以对嵌套的列表应用 flatMap
,并按 status
值进行过滤:
String[] failureMessages = data.getSubscriberCriteriaList()
.stream() // Stream<subscriberList>
.flatMap(sl -> sl.getSubscriberCriteriaList().stream()) // Stream<SubscriberCriteriaList>
.filter(scl -> "FAIL".equals(scl.getStatus()))
.map(SubscriberCriteriaList::getMsg) // 映射为消息
.distinct() // (可选)如果需要,去除重复项
.toArray(String[]::new);
英文:
Assuming that the top-level object has type Data
, and appropriate getters are available in all the mentioned classes, it is possible to apply flatMap
to the nested lists and filter by status
value:
String[] failureMessages = data.getSubscriberCriteriaList()
.stream() // Stream<subscriberList>
.flatMap(sl -> sl.getSubscriberCriteriaList().stream()) // Stream<SubscriberCriteriaList>
.filter(scl -> "FAIL".equals(scl.getStatus()))
.map(SubscriberCriteriaList::getMsg) // map to messages
.distinct() // (optionally) remove duplicates if necessary
.toArray(String[]::new);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论