使用Java Streams在复杂数据结构中搜索

时间:2017-08-30 06:26:03

标签: java java-8

[
 {"productStatus":
    [
     {"status": "spoilt"},
     {"status": "used"}
    ],
 "productMsg":
    [
    {"msg": "Valid"}
    ]
 },
 {"productStatus":
    [
     {"status": "new"},
    ],
 "productMsg":
    [
    {"msg": "Ok"},
    {"customMsg" : "blah blah"}
    ]
 }
]

我将上述数据存储在List<Map<String, List<Map<String, String>>>>中;

例如:

val is represented by Lombok library.
val firstObj = ImmutableList.of(ImmutableMap.of("status", "spoilt"),
                ImmutableMap.of("status", "new"),
                ImmutableMap.of("status", "used"));
val secondObj = ImmutableList.of(ImmutableMap.of("msg", "Valid"));
val productStatus1 = ImmutableMap.of("productStatus", firstObj,
                "productMsg", secondObj);

val firstObj_1 = ImmutableList.of(ImmutableMap.of("status", "new"));
val secondObj_2 = ImmutableList.of(ImmutableMap.of("msg", "Ok"));
val productStatus_2 = ImmutableMap.of("productStatus", firstObj_1,
                "productMsg", secondObj_2);

val testObj = ImmutableList.of(productStatus1, productStatus_2);

我需要找出productStatus是否是新的,然后获取所有productMsgs。例如,在我给出的示例中: 我将需要

的地图
{"msg": "Ok"},
{"customMsg" : "blah blah"}

对于状态为new的每个productStatus,请继续将其添加到列表中。基本上我需要返回List<Map<String, String>>

我知道如何在传统的Java for循环方法中实现这一点,我认为这样做太笨拙和冗长。使用Streams有一种巧妙的方法吗?

1 个答案:

答案 0 :(得分:2)

未经测试,但我认为这会做你想要的:

<!DOCTYPE html>
<html>
<head>
<style> 
input:enabled {
    background: #ffff00;
}

input:disabled {
    background: #dddddd;
}
div:disabled {
    opacity: 0.4;
    filter: alpha(opacity=40); /* For IE8 and earlier */
}
</style>
</head>
<body>

<form action="">
First name: <input type="text" value="Mickey"><br>
Last name: <input type="text" value="Mouse"><br>
Country: <input type="text" value="Disneyland" disabled><br>
Password: <input type="password" name="password" value="psw" disabled><br>
E-mail: <input type="email" value="john@doe.com" name="usremail">
</form>
<div disabled="disabled">should be transparent</div>
</body>
</html>