Java 8迭代嵌套循环并获取详细信息

huangapple go评论101阅读模式
英文:

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&lt;subscriberList&gt; subscriberCriteriaList;

}

public class subscriberList{

private String mdn;
private List&lt;SubscriberCriteriaList&gt; subscriberCriteriaList;

}

public class SubscriberCriteriaList{

private String status;
private String msg;

}

Sample json structure

   {
&quot;subscriberList&quot;: [
  {       
    &quot;mdn&quot;: &quot;string&quot;,
    &quot;subscriberCriteriaList&quot;: [
      {
        &quot;status&quot;: &quot;FAIL&quot;,
        &quot;msg&quot;: &quot;error message&quot;
      }
    ]
  }
]
}

答案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&lt;subscriberList&gt;
    .flatMap(sl -&gt; sl.getSubscriberCriteriaList().stream()) // Stream&lt;SubscriberCriteriaList&gt;
    .filter(scl -&gt; &quot;FAIL&quot;.equals(scl.getStatus()))
    .map(SubscriberCriteriaList::getMsg) // map to messages
    .distinct() // (optionally) remove duplicates if necessary
    .toArray(String[]::new);

huangapple
  • 本文由 发表于 2020年10月26日 00:51:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64526325.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定