我已经使用 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<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
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.flatMap()
返回一个流,其中包含将此流的每个元素替换为映射流的内容的结果,该映射流是通过将提供的映射函数应用于每个元素而生成的。
List<List<LinkedHashMap<String,String>>> productsMasterMap = ...;
List<LinkedHashMap<String, String>> listOfMaps = productsMasterMap.stream()
.flatMap(Collection::stream)
.filter(element -> current filter condition)
.toList();
作为旁注,我将使用自定义类,而不是
Map
,元素具有相同的属性。这将使代码更具可读性。
正如@Chaosfire提到的,你需要平面图。 对于您的情况,如果您需要内部列表元素作为过滤结果,则情况如下:
String searchId = "PdmarticleID";
Object 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();