Java-根据条件迭代地图列表

时间:2019-02-06 16:01:45

标签: java collections hashmap java-stream

我具有以下json结构

{
  "CreateDtTm": "2019-02-06T10:34:06",
  "AcftType": "Event",
  "EqpCd": "73Y",
  "TailNbr": "N26226",
  "docType": "TailClndr",
  "TailActvy": [
    {
      "FlightLeg": {
        "DepDlyMin": "1",
        "TaxiInMin": "0",
        "AccumTm": -99000000,
        "Indicators": {
          "In": "0",
          "ArrRtbl": "0",
          "Cncl": "1"
        }
      }
    },
    {
      "FlightLeg": {
        "DepDlyMin": "1",
        "TaxiInMin": "0",
        "AccumTm": -99000000,
        "Indicators": {
          "In": "1",
          "ArrRtbl": "0",
          "Cncl": "0"
        }
      }
    }    
  ]
}

我需要迭代地图,并以“ Indicators”“ IN”为1提取“ FlightLeg”。采用传统方式,如下所示-

List<LinkedHashMap<String, Object>> tailActiviyList = (List<LinkedHashMap<String, Object>>) aircraftRoutingInfoMap
        .get("TailActvy");

for (HashMap<String, Object> flightActivityMap : tailActiviyList) {
    if (flightActivityMap.containsKey("FlightLeg")) {
        HashMap<String, Object> flightLegMap = (HashMap<String, Object>) flightActivityMap.get("FlightLeg");
        HashMap<String, Object> flightIndicators = (HashMap<String, Object>) flightLegMap.get("Indicators");

        if(flightIndicators.get("In").equals("0") && flightIndicators.get("Cncl").equals("0"))
        {
            aircraftRoutingList.add(flightLegMap);
        }
    }
}

这可以使用Java Stream来实现。

1 个答案:

答案 0 :(得分:0)

从概念上讲,您从流中查找的是使用filtermap

List<Map<String, Object>> aircraftRoutingList = tailActiviyList.stream()
        .filter(f -> f.containsKey("FlightLeg")
                && ((Map<String, Object>) ((Map<String, Object>) f.get("FlightLeg")).get("Indicators")).get("In").equals("0")
                && ((Map<String, Object>) ((Map<String, Object>) f.get("FlightLeg")).get("Indicators")).get("Cncl").equals("0")
        )
        .map(m -> (Map<String, Object>) m.get("FlightLeg"))
        .collect(Collectors.toList());

但是,仅看一看,首先会建议使用类对对象进行建模,然后在更大程度上进一步提高代码的可读性。