我已经使用 JSON 路径解析了以下 JSON 字符串:
{
[
[
{
"ID": "ExternalKey",
"Name": "ExternalKey",
"Label": "ExternalKey",
"ExternalKey": "",
"TranslatedName": "ExternalKey",
"Type": "caption",
"Self": "https://aqb629.saas.contentserv.com/admin/rest/product/Attribute/ExternalKey",
"Value": "VSCHL01",
"FormattedValue": "VSCHL01"
},
{
"ID": "PdmarticleID",
"Name": "PdmarticleID",
"Label": "PdmarticleID",
"ExternalKey": "",
"TranslatedName": "PdmarticleID",
"Type": "_id",
"Self": "",
"Value": 99942,
"FormattedValue": 99942
}
],
[
{
"ID": "ExternalKey",
"Name": "ExternalKey",
"Label": "ExternalKey",
"ExternalKey": "",
"TranslatedName": "ExternalKey",
"Type": "caption",
"Self": "",
"Value": "VSCHL02",
"FormattedValue": "VSCHL02"
},
{
"ID": "PdmarticleID",
"Name": "PdmarticleID",
"Label": "PdmarticleID",
"ExternalKey": "",
"TranslatedName": "PdmarticleID",
"Type": "_id",
"Self": "",
"Value": 99944,
"FormattedValue": 99944
}
]
]
}
我在 Java 中得到以下
List
中的 List
:
List<List<LinkedHashMap<String,String>>> productsMasterMap = jsonContext.read(jsonPath);
我想通过流进行搜索,其中 ID = PdmArticleID 和 Value=99924 我会得到以下结构:
[
{
"ID": "ExternalKey",
"Name": "ExternalKey",
"Label": "ExternalKey",
"ExternalKey": "",
"TranslatedName": "ExternalKey",
"Type": "caption",
"Self": "https://aqb629.saas.contentserv.com/admin/rest/product/Attribute/ExternalKey",
"Value": "VSCHL01",
"FormattedValue": "VSCHL01"
},
{
"ID": "PdmarticleID",
"Name": "PdmarticleID",
"Label": "PdmarticleID",
"ExternalKey": "",
"TranslatedName": "PdmarticleID",
"Type": "_id",
"Self": "",
"Value": 99942,
"FormattedValue": 99942
}
]
这是一个
List<LinkedHashMap<String,String>>
对象。我怎样才能做到这一点?我尝试过以下方法:
List<LinkedHashMap> listOfMaps =
productsMasterMap.stream().filter(listOfHashMaps->
listOfHashMaps.stream().filter(m->m.get("ID").equals("PdmarticleID") &&
m.get("Value").equals("99945"))
map(m->m).collect(Collectors.toList());
我想获取条件为真的内部列表元素。
您可以在内部流上使用 Stream.anyMatch() 来查找是否有任何地图符合您的条件:
返回此流的任何元素是否与提供的谓词匹配。如果不需要确定结果,则可能不会评估所有元素上的谓词。
然后你可以使用 Stream.findFist() 来获取第一个匹配:
返回一个描述该流的第一个元素的可选值,如果流为空,则返回一个空的可选值。
List<List<LinkedHashMap<String,String>>> productsMasterMap = ...;
Optional<List<LinkedHashMap<String, Object>>> listOfMaps = productsMasterMap.stream()
.filter(listOfHashMaps -> listOfHashMaps.stream()
.anyMatch(map -> map.get("ID").equals("PdmarticleID") && map.get("Value").equals(99944)))
.findFirst();
//handle the Optional
如果可能有超过 1 场比赛并且您关心这些比赛,而不是
findFirst
收集到列表。
作为旁注,我将使用自定义类,而不是
Map
,元素具有相同的属性。这将使代码更具可读性。
正如@Chaosfire提到的,你需要平面图。 对于您的情况,如果您需要内部列表元素作为过滤结果,则情况如下:
String searchId = "PdmarticleID";
String searchValue = "99924";
Optional<Map<String, Object>> result = productsMasterMap.stream()
.flatMap(List::stream) // Flatten the nested lists
.filter(map -> searchId.equals(map.get("ID")) && searchValue.equals(map.get("Value")))
.findFirst();