嵌套地图上的Java8流操作 - Map <string,list <map =“”>&gt;

时间:2018-05-07 11:21:29

标签: java-8 hashmap java-stream

我有Map以下类型的Map<String, List<Map<String, String>>> - "1" - [M1, M1, M3] "2" - [M1, M2, M3] "3" - [M4] "4" - [M2, M5] 。它包含以下格式的元素:

"1","2","3","4"

其中,

Map<String, List<Map<String, String>>>outerKey外部地图的键。我们称他们为M1。因此,outerKey&#39; s "1", "2"都是M2。对于"2", "4" M1, M2, M3, M4, M5

Map<String, List<Map<String, String>>>k1

的内部地图

内部地图之间区别的主要关键是k1密钥。 (除M1外,内部地图中还有其他条目。例如:

{ "k1": "m1", "k2": "n1" } - M2{ "k1": "m2", "k2": "n2" } - outerKey

现在,我想提取一份独特的内部地图列表及其最高M1 - "2" M2 - "4" M3 - "2" M4 - "3" M5 - "4" 。例如,对于上述输入,输出应为:

outerKey

{ "1": [{ "k1": "m1", "k2": "n1" }, { "k1": "m1", "k2": "n1" }, { "k1": "m2", "k2": "n2" }], "2": [{ "k1": "m1", "k2": "n1" }, { "k1": "m2", "k2": "n2" }, { "k1": "m3", "k2": "n3" }], "3": [{ "k1": "m4", "k2": "n4" }], "4": [{ "k1": "m2", "k2": "n2" }, { "k1": "m5", "k2": "n5" }] } Use the following code to convert it into Map: (JSONObject)JSONValue.parseWithException(data)也可以插入地图中,以便我们可以获得地图列表。

因此,对于样本输入:

&#13;
&#13;
[{
    	"k1": "m1",
    	"k2": "n1",
    	"outerKey": "2"
    }, {
    	"k1": "m2",
    	"k2": "n2",
    	"outerKey": "4"
    }, {
    	"k1": "m3",
    	"k2": "n3",
    	"outerKey": "2"
    }, {
    	"k1": "m4",
    	"k2": "n4",
    	"outerKey": "3"
    }, {
    	"k1": "m5",
    	"k2": "n5",
    	"outerKey": "4"
    }]
&#13;
&#13;
&#13;

输出将是:

&#13;
&#13;
Map<String, String>
&#13;
&#13;
&#13;

我在java8中遇到这个问题?

我尝试通过执行以下操作获取outerKey的流并同时添加条目(a.entrySet().stream().flatMap(e -> e.getValue().stream(m -> m.put("outerKey",e.getKey()))) ):

Stream<String>

但它会返回map.put,因为Stream<Map>会返回与该键相关联的先前值。

因此,我无法添加entry <?php session_start(); require_once("connect.php"); $table = $_SESSION['title']; function delete($table) { if (isset($_SESSION['id']) && is_numeric($_SESSION['id'])) { $id = $_SESSION['id']; $query = "DELETE FROM $table WHERE id=$id"; if (mysqli_query($mysqli, $query)) { echo"Deleted successfully"; header("location:teams.php"); } else { echo"Unable to delete"; header("location:teams.php"); } } } delete("$table"); ?> 。我哪里错了?

1 个答案:

答案 0 :(得分:0)

以下作品:

a.entrySet()
            .stream()
            .flatMap(e -> e.getValue().stream().map(m -> {m.put("outerKey",e.getKey());return m;}))
            .collect(
                groupingBy(m -> m.get("k1"),collectingAndThen(maxBy(comparing(m -> m.get("outerKey"))),o -> ((Optional)o).get())
                )
            )
            .values()

输出:

[{outerKey=2, k1=m1, k2=n1}, {outerKey=4, k1=m2, k2=n2}, {outerKey=2, k1=m3, k2=n3}, {outerKey=3, k1=m4, k2=n4}, {outerKey=4, k1=m5, k2=n5}]