【发布时间】:2018-11-26 12:58:29
【问题描述】:
我需要一种使用 java 8 流将下面提到的 JSON 转换为 List> 的方法。这里有一些挑战,有一些我需要并且需要忽略其余的属性。我基本上需要重量和产品。
[
{weight=30, type=cosmatic, product=product-1,product-2,product-3},
{weight=15, type=commercia, product=product-1,product-3},
{weight=50, ramdonField=newValue, product=product-1,product-4},
{weight=2, product=product-1,product-2},
{weight=15, product=product-1},
{weight=25, product=product-1},
{weight=2, product=product-1}
]
我可以通过编写下面的代码来实现这一点,只是想知道是否有更有效的方法来做到这一点。
List<Map<String, Object>> franchiseRulesTemp = new LinkedList<>();
for (Entry<String, Object> test : config.entrySet()) {
try {
if (test.getValue() instanceof Map<?, ?> && ((Map<String, Object>) test.getValue()).containsKey("product")) {
Map<String, Object> mapper = ((Map<String, Object>) test.getValue());
String productList = (String) mapper.get("product");
String[] productListArray = productList.split(",");
for (String product : productListArray) {
Map<String, Object> gameDetails = new HashMap<>();
gameDetails.putAll((Map<String, Object>) test.getValue());
gameDetails.put("product",product);
gameDetails.put("ruleName", test.getKey());
franchiseRulesTemp.add(gameDetails);
}
}
} catch (Exception exception) {
System.out.println("Occured" + exception.getMessage());
}
}
提前致谢。
【问题讨论】:
-
到目前为止你尝试了什么?
-
但实际上,您应该开始考虑类和对象,而不是考虑映射。定义一个具有两个类型化属性
weight和product的类,并使用它而不是使用映射。 -
@user2681668,您添加了额外的要求,我们仍然没有看到您的任何尝试。注意添加一些。
标签: java java-8 java-stream